Reduce parent div to an unknown number of floating children (css or js)

I have a parent div (display: table) that wraps an unknown number of floating children. Now I want it to always have the width of the child lines.

In other words: if the parent div is wider or narrower than a multiple of its child, the unused space remains in the parent div. “How can I avoid this?”

Is this only possible with css, or do I need JS to calculate the width of the lines inside and provide it to the parent div?

Here's the simplified code:

.wrapper { border: 1px solid black; display:table; width:90%; } .child { float:left; width: 100px; background-color:red; margin: 0 10px 10px 0; } 
 <div class="wrapper"> <div class="child">Text</div> <div class="child">Text</div> <div class="child">Text</div> <div class="child">Text</div> <div class="child">Text</div> <div class="child">Text</div> </div> 

Play around with the width of your browser to see unused empty space on the right side.

+6
source share
2 answers

You can try: demo

 .wrapper { border: 1px solid black; width:auto; overflow:auto; display: flex; flex-flow: row wrap; justify-content: space-between; } .child { display:inline-block; width: 15%; background-color:red; margin: 0 10px 10px 0; order: 1px solid #333; position: relative; } 
+2
source
  .wrapper { border: 1px solid black; display:table; width: 90%; margin-bottom: -10px; } .child { box-sizing: border-box; float:left; width: 24.25%; background-color:red; margin: 1% 1% 0 0; } .child:nth-child(-n+4){ margin-top: 0; } .child:nth-child(4n) { margin-right: 0px; } 

Check out this demo http://jsfiddle.net/wtxafjw0/1/

This assumes a minimum of 4 children, and the child’s width is% to make them occupy the entire horizontal space.

0
source

Source: https://habr.com/ru/post/983213/


All Articles