Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only have margin between child and not with parent in CSS?

This is my goal: have no margin between a child an a parent, and 25px margin between childs in the parent. See explaining image:

enter image description here

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.

like image 556
moffeltje Avatar asked Oct 23 '15 08:10

moffeltje


2 Answers

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>
like image 76
Kristijan Iliev Avatar answered Sep 21 '22 18:09

Kristijan Iliev


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

like image 32
Vucko Avatar answered Sep 23 '22 18:09

Vucko