This is my goal: have no margin between a child an a parent, and 25px
margin between childs in the parent. See explaining image:
I have this HTML code:
<div id="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
and this CSS:
#parent{
width: 200px;
height: 405px;
}
.child{
width: 50px;
height: 180px;
}
My question is: What is the best way to add the margin to every child?
I could do:
<div class="child" style="margin: 0px 25px 25px 0px"></div>
But then I have to do that to every child, and it gets harder when I have a lot of Children.
Try using display: flex
for your parent div and align
and justify
your content with space-between
.
Try it in the snippet:
#parent{
width: 200px;
height: 400px;
border: 1px solid black;
display: flex;
justify-content: space-between;
align-content: space-between;
flex-wrap: wrap;
}
.child{
width: 50px;
height: 180px;
border: 1px solid lightcoral;
display: inline-block;
}
<div id="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
If you have 3 div
childs in every row, then you can use:
#parent > div:not(:first-of-type):not(:nth-of-type(2)):not(:nth-of-type(3)){
margin-top: 25px; /* add margin-top to every div except the first 3 */
}
#parent > div:nth-of-type(3n+2){
/* add margin-left and margin-right to every second div in every row */
margin-left: 25px;
margin-right: 25px;
}
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With