I want to do something like this image,
but I do not know how to ensure that between each column there is a separation of 20px
between each column. I am doing margin-right: 20px;
but I will have a problem with the last column.
What is the best practice to solve this using flexbox
?
.flex_container{
display:flex;
border:1px solid red;
width:100%;
}
.flex_container div{
width:100%;
border:1px solid blue;
margin-right: 20px;
background:yellow;
height:400px;
}
<div class="flex_container">
<div>col 1</div>
<div>col 2</div>
<div>col 3</div>
<div>col 4</div>
</div>
CodePudding user response:
This workaround targets all children but the last one :)
.flex_container{
display:flex;
border:1px solid red;
width:100%;
}
.flex_container div{
width:100%;
border:1px solid blue;
background:yellow;
height:400px;
}
.flex_container div:not(:last-child) {
margin-right: 20px;
}
<div class="flex_container">
<div>col 1</div>
<div>col 2</div>
<div>col 3</div>
<div>col 4</div>
</div>
CodePudding user response:
Just add gap:20px;
to your flex container
.flex_container{
display:flex;
border:1px solid red;
width:100%;
gap: 20px;
}
.flex_container div{
width:100%;
border:1px solid blue;
/*margin-right: 20px; not necessary*/
background:yellow;
height:400px;
}
<div class="flex_container">
<div>col 1</div>
<div>col 2</div>
<div>col 3</div>
<div>col 4</div>
</div>
CodePudding user response:
Most people have already pointed to setting "gap" on the container. But also, remove width and margin from the flex items and set flex-grow instead.
.flex_container{
display:flex;
border:1px solid red;
width:100%;
gap: 20px;
}
.flex_container div{
border:1px solid blue;
background:yellow;
height:400px;
flex-grow: 1;
}
CodePudding user response:
You can use justify-content
property too to have a equal space like in below snippet :
See more about justify-content
here
But as you use it you will see it works when
width
have to be in absolute values
.flex_container {
display: flex;
border: 1px solid red;
width: 100%;
flex-flow:row;
justify-content:space-between;
}
.flex_container div {
width: 100px;
border: 1px solid blue;
background: yellow;
height: 400px;
}
<div class="flex_container">
<div>col 1</div>
<div>col 2</div>
<div>col 3</div>
<div>col 4</div>
</div>