The built-in div block with "white space: normal" exceeds the width of the parent element with "white-space: nowrap"

I am trying to arrange several elements in a row so that they all match the width of the container. To prevent word wrapping, I added the parent element "white-space: nowrap" and added the children "white-space: normal" so that they could wrap the text (optional).

The problem is that with this configuration, the right most of the children sometimes exceed the width of the parent.

expected vs actual

HTML:

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

CSS

 #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; } 

http://jsfiddle.net/7e5TU/1/ (change the length of the text if the problem does not appear immediately).

I know that I can solve it using a table and possibly with a float on the left and on the right โ€œoverflow: hiddenโ€, but I see no reason why this should not work.

Can anyone give some ideas? I basically would like to understand that in the box, the model causes this behavior. Thanks!

+6
source share
3 answers

I agree with @hashem This is the expected behavior. Using white-space: nowrap; for the parent, you collapsed the spaces between the inline(-block) elements. white-space handles children, not the element itself.

Well, if you still need to fix it, you can add width to the second child so that it fits inside the container .

fiddle

eg.

 .child2 { width: 70%; } 
+1
source

If you want to use flexbox ( https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes ), you can do it like this: http://jsfiddle.net/7e5TU/6/

HTML

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

CSS

 #container { width: 200px; background: yellow; border: 1px solid brown; padding: 5px; display: flex; flex-direction: row } .child1, .child2 { display: block; border: 1px solid red; vertical-align: top; } .child1 { min-width: 50px; } 
+1
source

You can do this with CSS display: table. Thus, detailing is not required. This ensures that the elements remain in the line and the text is fully anchored to the width of the parent container.

HTML

 <div class='container'> <div class='field'> <div class='data'> child 1 </div> </div> <div class='field'> <div class='data'> child 2 text that might be long enough to wrap, but still exceed the parent </div> </div> </div> 

CSS

 .container { display: inline-table; border-spacing: 4px; background: yellow; border: 1px solid brown; padding: 5px; } .field { display: table-cell; } .data { border: 2px solid red; padding: 3px; } 
0
source

All Articles