如何使用Flexbox在每个断点处使div居中?

时间:2019-01-24 08:14:33

标签: html css css3 flexbox

我想将div居中放置在当前位置,但问题是当有两个div时它们与上面的矩形不对齐。我知道它们将与justify-content:space between对齐,但是当div是行中唯一的div时,这将防止div居中。我想做什么?

.wrapper {
  max-width: 1000px;
  margin: 0 auto
}

.title {
  width: 100%;
  height: 100px;
  background: green;
  margin-bottom: 30px;
}

.outer {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.col {
  /*            flex-grow, flex-shrink, flex-basis*/
  flex: 0 0 31%;
  margin: 0 1% 2% 1%;
  height: 300px;
}

.col1 {
  background-color: red;
}

.col2 {
  background-color: blue
}

.col3 {
  background: black;
}

@media only screen and (max-width: 960px) {
  .col {
    flex: 0 0 48%;
  }
}

@media only screen and (max-width: 480px) {
  .col {
    flex: 0 0 100%;
  }
}
<div class="wrapper">
  <div class="title">

  </div>
  <div class="outer">
    <div class="col col1">

    </div>
    <div class="col col2">

    </div>
    <div class="col col3">

    </div>

  </div>

</div>

1 个答案:

答案 0 :(得分:0)

您可以将margin-left: auto设置为.col1,将margin-right: auto设置为.col2以分别按下div。

.wrapper {
  max-width: 1000px;
  margin: 0 auto
}

.title {
  width: 100%;
  height: 100px;
  background: green;
  margin-bottom: 30px;
}

.outer {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.col {
  /*            flex-grow, flex-shrink, flex-basis*/
  flex: 0 0 31%;
  margin: 1% 0 2% 0;
  height: 300px;
}

.col1 {
  background-color: red;
  margin-right: auto;
}

.col2 {
  background-color: blue;
  margin-left: auto;
}

.col3 {
  background: black;
}

@media only screen and (max-width: 960px) {
  .col {
    flex: 0 0 48%;
  }
}

@media only screen and (max-width: 480px) {
  .col {
    flex: 0 0 100%;
  }
}
<div class="wrapper">
  <div class="title">

  </div>
  <div class="outer">
    <div class="col col1">

    </div>
    <div class="col col2">

    </div>
    <div class="col col3">

    </div>

  </div>

</div>