【问题标题】:Center grid item on wrap包裹中心网格项目
【发布时间】:2020-07-11 12:29:52
【问题描述】:

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

【问题讨论】:

  • 它落入wraper 框内,因此它有一个假想的第四个框挡住它。
  • @Mech 那我该如何解决呢?
  • 只是一个友好的建议:正确的拼写是“wrapper”。

标签: html css css-grid centering


【解决方案1】:

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

.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>

【讨论】:

  • 好的,我试过了,但是现在当我缩小到一个列时,这一切都很奇怪,我如何默认一切恢复?
  • 看我贴的完整代码sn-p。它包括以下媒体查询的重置。
  • 哎呀没看到,但谢谢你的帮助,你是一个救生员
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 2018-04-15
  • 2017-01-04
  • 2019-03-26
  • 2016-11-12
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多