猿问

围绕网格项目居中

我想弄清楚如何将第三个 div 居中。所以在全宽上我在网格中有 3 个盒子。它们的宽度为 400 像素。当宽度为 1220px 时,会变成连续 2 个框。所以我的第三个框是靠左对齐的。我如何将其居中而不破坏宽度。因为我尝试过margin: 0 auto,它只是使它与里面的东西一样宽。


这是我的代码:


.wraper {

  display: grid;

  grid-template-columns: 400px 400px 400px;

  grid-gap: 10px;

  grid-template-columns: repeat(3, 400px);

}


.box {

  background-color: red;

  height: 200px;

}


@media (max-width: 1220px) {

  .wraper {

    grid-template-columns: repeat(2, 400px);

  }

}


@media (max-width: 810px) {

  .wraper {

    grid-template-columns: repeat(1, 400px);

  }

}


@media (max-width: 400px) {

  .wraper {

    grid-template-columns: repeat(1, 300px);

  }

}

<div class="block bg-success">

  <h1>Projects</h1>

  <div class="wraper">

    <div class="box">A</div>

    <div class="box">B</div>

    <div class="box">C</div>

  </div>

</div>


一只萌萌小番薯
浏览 116回答 1
1回答

SMILET

在 1220px 媒体查询中,添加一条规则以使第三个 div 居中。@media (max-width: 1220px) {&nbsp; .wrapper {&nbsp; &nbsp; grid-template-columns: repeat(2, 400px);&nbsp; }&nbsp; &nbsp;/* NEW */&nbsp; .box:last-child {&nbsp; &nbsp; grid-column: 1 / 3;&nbsp; &nbsp; justify-self: center;&nbsp; &nbsp; width: 400px;&nbsp; }}jsFiddle 演示.wrapper {&nbsp; display: grid;&nbsp; grid-template-columns: 400px 400px 400px;&nbsp; grid-auto-rows: 200px;&nbsp;&nbsp;&nbsp; grid-gap: 10px;&nbsp; grid-template-columns: repeat(3, 400px);}@media (max-width: 1220px) {&nbsp; .wrapper {&nbsp; &nbsp; grid-template-columns: repeat(2, 400px);&nbsp; }&nbsp; &nbsp;/* NEW */&nbsp; .box:last-child {&nbsp; &nbsp; grid-column: 1 / 3;&nbsp; &nbsp; justify-self: center;&nbsp; &nbsp; width: 400px;&nbsp; }}@media (max-width: 810px) {&nbsp; .wrapper {&nbsp; &nbsp; grid-template-columns: repeat(1, 400px);&nbsp; }&nbsp; &nbsp;/* RESET */&nbsp; .box:last-child {&nbsp; &nbsp; grid-column: auto;&nbsp; &nbsp; justify-self: stretch;&nbsp; &nbsp; width: auto;&nbsp; }}@media (max-width: 400px) {&nbsp; .wrapper {&nbsp; &nbsp; grid-template-columns: repeat(1, 300px);&nbsp; }}.box {&nbsp; background-color: red;}<div class="block bg-success">&nbsp; <h1>Projects</h1>&nbsp; <div class="wrapper">&nbsp; &nbsp; <div class="box">A</div>&nbsp; &nbsp; <div class="box">B</div>&nbsp; &nbsp; <div class="box">C</div>&nbsp; </div></div>
随时随地看视频慕课网APP

相关分类

Html5
我要回答