如何在最大宽度的容器内制作网格项目以覆盖整个宽度?

问题描述 投票:0回答:1

CSS网格位于带有max-width的页面上:

enter image description here

body {
  outline: 1px solid black;
}

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

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
}

.first-grid-item {
  grid-column: 1 / -1;
  background-color: #ccc;
}

.second-grid-item {
  grid-column: 1 / -1;
  background-color: tomato;
}

@media (min-width: 576px) {
  .first-grid-item {
    grid-column: 1 / 9;
  }
  .second-grid-item {
    grid-column: 9 / 13;
  }
}
<div class="max-width">
  <div class="grid">
    <div class="first-grid-item">First</div>
    <div class="second-grid-item">Second</div>
  </div>
</div>

在较小的屏幕上,布局发生变化,第二个网格项放置在第一个网格项下方:

enter image description here

现在,出现了一项新要求,即在较小的屏幕上为第二个项目添加全角背景色,因此看起来像这样:

enter image description here

您将如何实现?


[Notes

  • 网格可以出现在页面中间的某处,不一定是页面上的唯一元素。例如:here
css css-grid
1个回答
0
投票

我唯一想到的方法是在::before上使用::aftersecond-grid-item元素,并使body溢出。您实际上需要在主体上设置overflow: hidden才能起作用,因此它不会设置水平滚动:

body {
  outline: 1px solid black;
  overflow: hidden;
}

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

.grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
}

.first-grid-item {
  grid-column: 1 / -1;
  background-color: #ccc;
}

.second-grid-item {
  grid-column: 1 / -1;
  background-color: tomato;
  position: relative;
}

.second-grid-item::before,
.second-grid-item::after {
  content: '';
  display: block;
  position: absolute;
  left: -50%;
  top: 0;
  width: calc( 100% - 200px);
  height: 100%;
  background: powderblue;
}

.second-grid-item::after {
  left: auto;
  right: -50%;
}

@media (min-width: 576px) {
  .first-grid-item {
    grid-column: 1 / 9;
  }
  .second-grid-item {
    grid-column: 9 / 13;
  }
  .second-grid-item::before,
  .second-grid-item::after {
    display: none;
  }
}
<div class="max-width">
  <div class="grid">
    <div class="first-grid-item">First</div>
    <div class="second-grid-item">Pharetra eros mi eros accumsan dui. Pellentesque ipsum iaculis. Mi neque in nonummy venenatis vestibulum. Class egestas adipiscing nisl tellus quam ut in amet. Nostra nunc leo lorem eget ipsum elit eget metus nam sed pede. Nam nibh risus sit dui nullam.
      Consequat luctus tempus.
    </div>
  </div>
</div>

以下是一个代码笔:https://codepen.io/chrislafrombois/pen/qBOMopG

© www.soinside.com 2019 - 2024. All rights reserved.