2

In the standard configuration of WordPress, when centering figure elements containing img elements is chosen, these elements are automatically styled with display: table; margin-left: auto; margin-right: auto; to achieve horizontal centering. This styling is particularly useful for aligning the left edges of figcaption and img elements. Additionally, img elements are styled with max-width: 100%; height: auto to ensure they resize based on their aspect ratio derived from the width and height attributes, fitting the container's width at maximum. You can see the CSS definition here: https://github.com/WordPress/gutenberg/blob/a48a414853b7f66606393dd311556e6bdda1aa62/packages/block-library/src/image/style.scss#L61.

However, I've encountered an issue where if the image fails to load, the <img> element expands to the width specified in its width attribute, exceeding the parent's width. This seems to contradict the expected behavior given the max-width: 100%; rule.

Here’s a minimal code snippet without the WordPress context: https://codepen.io/frkly/pen/xbKbxxm

<style>
.container {
  width: 400px;
  border: solid 2px #f00;
}
.wp-block-image.aligncenter {
  display: table;
  margin: 0 auto 1em;
  max-width: 400px;
}
img {
  max-width: 100%;
  height: auto;
  background: #ccc;
}
</style>

<div class="container">
  <p>container, width:400px</p>
  
  <figure class="wp-block-image aligncenter">
    <img src="path/to/nonexistent/image.gif" width="600" height="50">
    <figcaption>Missing image, width="600"</figcaption>
  </figure>
</div>

I am looking for an explanation of this behavior and potential solutions that do not involve removing display: table. Does this have to do with specific CSS specifications or browser rendering quirks?

2
  • 3
    Can reproduce in Chrome only, Firefox doesn't appear to have the same issue. And in Chrome, the problem disappears, as soon as the missing image has a non-empty alt attribute. Commented Nov 28, 2024 at 12:26
  • @C3roe Based on the information you provided about the alt attribute, I've adjusted the CodePen to test different behaviors depending on the alt attribute value. Thanks for the insight! Commented Nov 29, 2024 at 0:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.