flexbox中的div居中

时间:2019-06-06 13:07:34

标签: html css flexbox

我正在使用flex,并且正在尝试实现某些目标。代码中显示了5个div。在min-width:768px中,我希望第四和第五个div居中。谁能帮我?这是代码:

css

.row{
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  }
  .col {
  position: relative;
  width: 100%;
  border:1px solid black;
  }
  @media  (min-width:576px){
    .col {
      -ms-flex: 0 0 33%;
      flex: 0 0 33%;
      max-width: 33%;
    }
  }
  @media (min-width: 768px){
    .col {
      -ms-flex: 0 0 19%;
      flex: 0 0 19%;
      max-width: 19%;
    }
  }

html

 <div class="row">
  <div class="col"><p>first</p>  </div>
  <div class="col"><p>second</p>  </div>
  <div class="col"><p>third</p>  </div>
  <div class="col"><p>fourth</p>  </div>
  <div class="col"><p>fifth</p>  </div>  
</div>

2 个答案:

答案 0 :(得分:1)

您可以在媒体查询中尝试以下操作:

  @media (min-width: 768px){
    .col {
      -ms-flex: 0 0 19%;
      flex: 0 0 19%;
      max-width: 19%;
    }

    .col:nth-child(4),
    .col:nth-child(5){
      text-align: center;
    }
  }

答案 1 :(得分:1)

这是您的代码,我已经更正了。您只需要一点CSS即可

 .row{
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
   justify-content: center;
  }
  .col {
  position: relative;
  width: 100%;
  border:1px solid black;
  }
  @media  (min-width:576px){
      .col {
      -ms-flex: 0 0 19%;
      flex: 0 0 19%;
      max-width: 19%;
    }
  }
  @media (min-width: 768px){


    .col {
      -ms-flex: 0 0 33%;
      flex: 0 0 33%;
      max-width: 33%;
    }
  }




 <div class="row">
  <div class="col"><p>first</p>  </div>
  <div class="col"><p>second</p>  </div>
  <div class="col"><p>third</p>  </div>
  <div class="col"><p>fourth</p>  </div>
  <div class="col"><p>fifth</p>  </div>  
</div>