为了账号安全,请及时绑定邮箱和手机立即绑定

围绕网格项目居中

围绕网格项目居中

一只萌萌小番薯 2023-10-24 17:40:05
我想弄清楚如何将第三个 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>
查看完整描述

1 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

在 1220px 媒体查询中,添加一条规则以使第三个 div 居中。


@media (max-width: 1220px) {

  .wrapper {

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

  }


   /* NEW */

  .box:last-child {

    grid-column: 1 / 3;

    justify-self: center;

    width: 400px;

  }

}

jsFiddle 演示

.wrapper {

  display: grid;

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

  grid-auto-rows: 200px;  

  grid-gap: 10px;

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

}


@media (max-width: 1220px) {

  .wrapper {

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

  }


   /* NEW */

  .box:last-child {

    grid-column: 1 / 3;

    justify-self: center;

    width: 400px;

  }

}


@media (max-width: 810px) {

  .wrapper {

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

  }


   /* RESET */

  .box:last-child {

    grid-column: auto;

    justify-self: stretch;

    width: auto;

  }

}


@media (max-width: 400px) {

  .wrapper {

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

  }

}


.box {

  background-color: red;

}

<div class="block bg-success">

  <h1>Projects</h1>

  <div class="wrapper">

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

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

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

  </div>

</div>


查看完整回答
反对 回复 2023-10-24
  • 1 回答
  • 0 关注
  • 63 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信