css - 全角元素破坏了使用 display: grid 创建的布局
问题描述
我有一个简单的布局,我使用由主元素和侧边栏组成的 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>
推荐阅读
- firebase - 在每个屏幕上的 fcm 通知上显示小吃栏
- grep - grep 用于具有特殊字符的模式并仅输出匹配的字符串
- scala - 如何查看 Scala 用于为案例类自动生成 apply 函数的代码?
- javascript - Can you tell moment.js what time zone a value is in?
- c++ - 写入二进制文件并从二进制文件中读取一条记录(一个对象)后,该记录的枚举类型最后一个属性为NULL(默认值)
- ios - Understanding typeallias CellProvider
- bash - How To Save Every Line Of A Text File Into Different Variables
- python-3.x - 在网站上执行 Selenium 操作后查找 HTML
- python - boto3 list_role_policies 返回空数组,或者我如何分离所有策略?
- angular - Angular query params as boolean type, not string