我有一个简单的布局,我用CSS网格创建了一个主要元素和侧边栏(请参阅代码段)。在侧边栏中,我有一个子元素,我想在移动设备上全宽(即忽略布局容器周围的填充)。
.full-width
元素确实全宽,但显然发生的是它使整个网格成为100vw
,这使得main
和aside
溢出.container
(灰色元素)。如何保持全宽并将main
和aside
保持在.container
的边界内?另一个要求是全宽度元素保留在文档的流程中(因此没有固定或绝对定位)。
.page {
background: pink;
padding: 30px;
}
.container {
display: grid;
grid-template-areas: "aside" "main";
background: grey;
padding: 60px 0;
}
aside {
background: yellow;
}
main {
background: green;
}
.full-width {
width: 100vw;
margin-left: -30px;
background: red;
}
<div class="page">
<div class="container">
<main>
<p>I'm the main content</p>
</main>
<aside>
<p>I'm the sidebar</p>
<div class="full-width">
<p>I'm the full width element</p>
</div>
</aside>
</div>
</div>
首先,简单的解决方案是将列设置为100%
以避免溢出:
.page {
background: pink;
padding: 30px;
}
.container {
display: grid;
grid-template-areas: "aside" "main";
grid-template-columns: 100%;
background: grey;
padding: 60px 0;
}
aside {
background: yellow;
}
main {
background: green;
}
.full-width {
width: 100vw;
margin-left: -30px;
background: red;
}
body {
margin:0;
}
<div class="page">
<div class="container">
<main>
<p>I'm the main content</p>
</main>
<aside>
<p>I'm the sidebar</p>
<div class="full-width">
<p>I'm the full width element</p>
</div>
</aside>
</div>
</div>
或者只是在两侧使用负边距来获得您想要的全宽:
.page {
background: pink;
padding: 30px;
}
.container {
display: grid;
grid-template-areas: "aside" "main";
background: grey;
padding: 60px 0;
}
aside {
background: yellow;
}
main {
background: green;
}
.full-width {
margin-left: -30px;
margin-right: -30px;
background: red;
}
body {
margin:0;
}
<div class="page">
<div class="container">
<main>
<p>I'm the main content</p>
</main>
<aside>
<p>I'm the sidebar</p>
<div class="full-width">
<p>I'm the full width element</p>
</div>
</aside>
</div>
</div>