首页 > 解决方案 > 包裹中心网格项目

问题描述

我想弄清楚如何将第三个 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>

标签: htmlcsscss-gridcentering

解决方案


在您的 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>


推荐阅读