简体   繁体   中英

How to make parent div fit its width to child items width with flexbox?

I have a flex parent div with more elements inside, but parent width doesnt fits to child elements, How can I fix it?

Basicaly I want to display a dinamical bidimensional matrix with its dimensions setted by the user, so the amount of elements inside will vary and there will be some line breaks like I show in the code bellow, also the child elements have its width and height fixed.

 .parent { display: flex; flex-wrap: wrap; background-color: silver; padding: 5px; border-radius: 10px; } .child { width: 40px; height: 40px; border-radius: 10px; background-color: gold; margin: 5px; } .line-break { width: 100%; }
 <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='line-break'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> </div>

Here is also a fiddle of the code: https://jsfiddle.net/NoisyApple/4g8n3vfL/3/

I expect the parent to automatically set its width to the elements inside it.

You can do this with a simple inline-block configuration:

 .parent { display:inline-block; background-color: silver; padding: 5px; border-radius: 10px; font-size:0; /*to remove whitespace:*/ margin:5px; } .child { height: 40px; width:40px; display:inline-block; vertical-align:top; border-radius: 10px; margin:5px; background-color: gold; font-size:initial; } .line-break { display:block; }
 <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='line-break'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> </div> <br> <div class='parent'> <div class='child'></div> <div class='child'></div> <div class='line-break'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> <div class='child'></div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM