Reputation: 6878
I have an empty div and I create other divs in it with javascript. I've set up my CSS so it will create a grid. My question is: how can I dynamically resize the divs so they evenly fill their container?
I tried to illustrate it better with a drawing but my drawing skills aren't that good. Hopefully you will understand what I want.
The black square is the parent div and the red squares are the children. When I create one div it should fill the parent div (with a little margin).
With two divs it will split the parent in half.
With 3 it will behave like you see in the upper right corner of the image, and so on for the others.
How could I accomplish this with CSS?
This is a game I have to make for school. This is a previous version but you get the idea of having squares in a div. Now the next task is to let the user chose how many squares they want to play with. But that has to be dynamic and they have to be able to choose numbers like 5 or 8. Not just 4, 9, 16, 25 etc. that's too easy.
https://luukwuijster.io/school/csp/kleurenspel/
Upvotes: 3
Views: 6324
Reputation: 2395
This type of layout can be achieved using CSS Flexbox.
First turn your wrapping element into a flexbox by adding display:flex
. Next add flex:1 1 auto
to your boxes to allow them to grow and shrink as needed to fill the space.
To keep your boxes from being squished into one line by flexbox, set a min-width
value on them. I've used min-width:30%
but this number can be changed to suit your needs. 30% will mean that the maximum number of boxes in a row at any time is 3 (as it is just below 1/3 or 33% of the container's width).
Try adding or removing boxes from the example code below.
#wrapper {
display:flex;
flex-wrap:wrap;
width:400px;
height:400px;
}
.box {
background-color:white;
border:1px solid black;
min-width:30%;
flex:1 1 auto;
}
<div id='wrapper'>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
<div class='box'></div>
</div>
Upvotes: 8