我正在修改CSS网格,并且想知道在调整屏幕大小时是否可以让嵌套网格移出其父网格。
我已尝试将grid-template-areas
更改为包含"子内容"但这似乎是错误的,并扰乱了网格。
例如,我已经设置了以下模板,并希望" subcontent" div(粉红色)替换" profile"媒体断点被击中时的区域。
有没有办法在纯CSS网格中执行此操作而不在JS中使用?
.wrapper {
margin: auto;
width: 80%;
background-color: #e0e0e0;
display: grid;
grid-template-columns: 3fr 1fr;
grid-template-rows: 2fr 1fr 4fr;
grid-template-areas:
" title profile"
" infobar infobar "
" maincontent sidebar ";
grid-gap: 1em;
}
.space {
background-color: #eeeeee;
grid-area: space;
}
.title {
grid-area: title;
background-color: red;
}
.profile {
grid-area: profile;
background-color: orange;
}
.infobar {
grid-area: infobar;
background-color: yellow;
}
.maincontent {
grid-area: maincontent;
display: grid;
grid-template-columns: 2fr 1fr;
grid-template-rows: 1fr 1fr;
grid-template-areas:
"subcontent1 subcontent2"
"subcontent1 subcontent2";
background-color: green;
}
.subcontent1 {
grid-area: subcontent1;
background-color: pink;
margin: 10px;
}
.subcontent2 {
grid-area: subcontent2;
background-color: pink;
margin: 10px;
}
.sidebar {
grid-area: sidebar;
background-color: blue;
}
@media screen and (max-width: 900px) {
.wrapper {
grid-template-columns: 2fr 1fr 1fr;
grid-template-areas:
"title title sidebar"
"infobar infobar infobar"
"profile maincontent maincontent"
"footer footer sidebar"
;
}
.maincontent{
display: block;
}
.subcontent {
grid-area: subcontent;
}
}

<div class="wrapper">
<div class="title">Title</div>
<div class="profile">Profile</div>
<div class="infobar">Info Bar</div>
<div class="maincontent">Main Content
<div class="subcontent1">Main1</div>
<div class="subcontent2">Main2</div>
</div>
<div class="sidebar">Sidebar</div>
</div>
&#13;
答案 0 :(得分:2)
我正在修补CSS网格,并想知道在调整屏幕大小时是否可以将嵌套网格移出其父网格。
就像你无法提取嵌套的flex容器那样它们可以作为祖先flex容器的flex项参与,你无法提取嵌套网格来做同样的事情。
您必须让布局中其他网格项的subcontent1
和subcontent2
兄弟姐妹重新定位。
我已尝试将
grid-template-areas
更改为包含“子内容”,但这似乎是错误的并且会破坏网格。
这种中断是有充分理由的。您发布了无效的字符串值。
这很好:
grid-template-areas: " title profile"
" infobar infobar "
" maincontent sidebar "
这也很好:
grid-template-areas: "subcontent1 subcontent2"
"subcontent1 subcontent2"
这很糟糕:
grid-template-areas: "title title sidebar"
"infobar infobar infobar"
"profile maincontent maincontent"
"footer footer sidebar"
您的上一次声明无效。
grid-template-areas
属性的字符串值必须形成矩形块。由于sidebar
以断开连接的方式出现两次,因此整个布局都会中断。
相反,请尝试这些:
grid-template-areas: "title title sidebar"
"infobar infobar infobar"
"profile maincontent maincontent"
"footer footer footer"
OR
grid-template-areas: "title title sidebar"
"infobar infobar infobar"
"profile maincontent maincontent"
"footer footer ..."
现在布局正常。 但是,HTML中实际上没有页脚,因此不会呈现任何内容。无论如何,存在无效字符串会破坏布局。
以下是更完整的解释: