Issue
I need to make a table which will contain up to 4 divs.
But the divs in that table always should use maximum of avaliable space.
And one one row should contain not more then 2 divs
For instance if table contains 2 divs it should look like this
If table has 3 divs then like this:
And if contains 4 then it should look like that
To achieve it i wrote this code:
<div
style={{
height: '58vh', border: '1px solid #d9d9d9',
borderRadius: '0px 0px 2px 2px',
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
}}
>
<div style={{background:'red', flex: 'auto', margin: '5px'}}
<div style={{background:'green', flex: 'auto', margin: '5px'}}
<div style={{background:'blue', flex: 'auto', margin: '5px'}}
<div style={{background:'pink', flex: 'auto', margin: '5px'}}
</div>
But i missing something here.
For 1 div and for 2 divs it works as planned.
But for more..
This is my result for 3 divs
And for 4 divs
Can anyone advice me please what should i change in this code?
PS. Please don't judge my unevenly drawn squeres :)
Solution
.container {
display: flex;
flex-wrap: wrap;
}
.inner {
flex-basis: 50%;
flex-grow: 1;
}
.inner:nth-of-type(1) {
background: red;
}
.inner:nth-of-type(2) {
background: gold;
}
.inner:nth-of-type(3) {
background: green;
}
.inner:nth-of-type(4) {
background: blue;
}
<div class="container">
<div class="inner">one</div>
<div class="inner">two</div>
<div class="inner">three</div>
<div class="inner">four</div>
</div>
I used the following steps to achieve your result.
- Make the container which contains the inner boxes as
flex
. - Give the container
flex-wrap: wrap
so that the inner boxes which do not have place on the same line, shift to the next line. - Give
flex-basis: 50%
to the inner boxes so that they take up 50% of the available space. - Give the inner boxes
flex-grow: 1
so that if the last box has any space left, it will take up all of it.
References:
- Flexbox
- flex-wrap
- flex-basis
- flex-grow
- (Extra) flex-shrink
PS: Try commenting the fourth inner box so that the third box will take up the whole horizontal space.
Answered By - deekeh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.