CSS网格位于带有max-width
的页面上:
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>
在较小的屏幕上,布局发生变化,第二个网格项放置在第一个网格项下方:
现在,出现了一项新要求,即在较小的屏幕上为第二个项目添加全角背景色,因此看起来像这样:
您将如何实现?
[Notes:
我唯一想到的方法是在::before
上使用::after
和second-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>