父div两端对齐内容:居中,最后一个孩子对齐:左

时间:2019-07-15 07:18:17

标签: html css

我正在尝试将所有子div居中对齐在父div中。如果我将display: flex;justify-content: center;放在我的<parent-div>

上,它就可以工作

但是问题是-我希望最后一个子div左对齐。 但是justify-content: center;将最后一个<child-div>对准中心。

我尝试从justify-content: center;中删除<parent-div>,并添加了margin: 0px 8px;以得到预期的输出。但是,它没有响应。

.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>

2 个答案:

答案 0 :(得分:0)

尝试删除justify-content并指定父div的width

.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>

答案 1 :(得分:-2)

只需在最后一项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>