Sasha Sasha - 3 months ago 18
CSS Question

An inline-block div with "white-space: normal" exceeds the width of a parent with "white-space: nowrap"

I'm trying to position a few elements in a row, so that they all fit in the width of the container. To prevent them from word-wrapping I added "white-space: nowrap" to the parent, and added "white-space: normal" to the children to allow them to wrap the text (as desired).

The problem is that with this configuration the right most child sometimes exceeds the width of the parent.

expected vs actual


<div id="container">
<div class="child">
child 1
<div class="child">
child 2 text that might be long enough to wrap, but still exceed the parent


#container {
white-space: nowrap;
width: 200px;
background: yellow;
border: 1px solid brown;
padding: 5px;

.child {
display: inline-block;
border: 2px solid red;
vertical-align: top;
white-space: normal;
} (change the length of the text if the problem doesn't appear straight away).

I know that I can solve it with a table, and probably with a float on the left child, and "overflow: hidden" on the right, but I see no reason why this should not work.

Could anyone provide some insights? I'd mostly love to understand what in the box model causes this behavior. Thanks!


I agree with @hashem That's the expected behavior. By using white-space: nowrap; for the parent, you've collapsed the whitespaces between inline(-block) elements. white-space treats the children, not the element itself.

Well if you still need a fix you can add width to second child to make it fit inside container.



    width: 70%;