-1

I am trying to center align all child divs inside parent div. And it works if I put display: flex; & justify-content: center; on my <parent-div>

But the problem is - I am expecting the last child div to be aligned to left. But justify-content: center; aligns the last <child-div> in the center.

I tried removing justify-content: center; from the <parent-div>, and added margin: 0px 8px; to get expected output. However, it is not responsive.

.parent-div {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  /* margin: 0px 8px; */
  justify-content: center;
}
.child-div {
  border: 1px dotted indianred;
  height: 222px;
  width: 156px;
}
<div class = "parent-div">
    <div class = "child-div">
        I am child 1
    </div>
    <div class = "child-div">
        I am child 2
    </div>
    <div class = "child-div">
       I am child 3
    </div>
</div>
Ngorld
  • 856
  • 7
  • 17

2 Answers2

0

Try to remove justify-content and specify width of the parent div.

.parent-div {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  border:1px solid;
  width: 316px;
  margin: 0 auto;
}
.child-div {
  border: 1px dotted indianred;
  height: 222px;
  width: 156px;
}
<div class="parent-div">
  <div class="child-div">
    I am child 1
  </div>
  <div class="child-div">
    I am child 2
  </div>
  <div class="child-div">
    I am child 3
  </div>
</div>
Chaska
  • 3,165
  • 1
  • 11
  • 17
-1

Just apply a magic line to the last item margin-right: auto

.parent-div {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  /* margin: 0px 8px; */
  justify-content: center;
}
.child-div {
  border: 1px dotted indianred;
  height: 222px;
  width: 156px;
}
.child-div:last-child{
  border: 1px dotted blue;
  margin-right: auto 
}
<div class = "parent-div">
    <div class = "child-div">
        I am child 1
    </div>
    <div class = "child-div">
        I am child 2
    </div>
    <div class = "child-div">
       I am child 3
    </div>
    <div class = "child-div">
       I am child 4
    </div>
</div>
Ngorld
  • 856
  • 7
  • 17
  • umm.. this is what I am getting and it is not aligning with the rest of child divs https://ibb.co/RhRZdzj – Ajinkya Bawaskar Jul 15 '19 at 07:35
  • You should to understand all child item always align center but the last child align left. That because the last item not align left same as another items. – Ngorld Jul 15 '19 at 07:39