Skip to content Skip to sidebar Skip to footer

Why Does These Inline-block Element Produce Extra Width?

This is a follow up from this question: Autofit text under image with only css Why does the inline-block divs in this code produce extra width on the right side of the elements? E

Solution 1:

The red portion of the item is an artifact of the browser not knowing how to correctly size the containers. It's using the length of the text to determine the width before the table layout is applied. If you know the width of the items, you can use this simpler approach:

.item {
  display: inline-block;
  background-color: blue;
  width: 120px;
}

.image {
  display: block;
  height: 120px;
}
<divclass="item"><imgsrc='http://i.imgur.com/nV2qBpe.jpg'class="image"><pclass='text'>Some text that may need to wrap into multiple lines</p></div><divclass="item"><imgsrc='http://i.imgur.com/nV2qBpe.jpg'class="image"><pclass='text'>Some text that may need to wrap into multiple lines</p></div><divclass="item"><imgsrc='http://i.imgur.com/nV2qBpe.jpg'class="image"><pclass='text'>Some text that may need to wrap into multiple lines</p></div><divclass="item"><imgsrc='http://i.imgur.com/nV2qBpe.jpg'class="image"><pclass='text'>Some text that may need to wrap into multiple lines</p></div>

I don't know off hand of a way to make the elements shrink to the smallest possible width while still containing all child elements.

Solution 2:

I modified @Brandon Gano's second answer. I used display: table-caption; on .text-wrapper.

Here's the CSS I modified from his jsfiddle:

.text-wrapper {
  overflow: hidden;
  display: table-caption;
  caption-side: bottom;
  height: 60px;             /* You may have to modify the height */background-color: blue;
}

And the updated jsfiddle.

Solution 3:

You're seeing whitespace added between the inline-block elements. You can remove the horizontal space between these items by removing all whitespace between the elements. e.g.:

<div>
  ...
</div><div>
  ...
</div><div>
  ...
</div>

Note that the closing tag is immediately followed by the next opening tag.

Post a Comment for "Why Does These Inline-block Element Produce Extra Width?"