我想使用CSS Grid的网格模板区域。
但问题是我正在使用的CMS正在添加大量额外的包装器。 有没有办法忽略额外的包装?因为它弄乱了漂亮的网格区域......
我正在尝试覆盖css网格的自动放置机制。 因此,任何位于中间且未分配特定网格区域的div将出现在网格的末尾,并且不会弄乱网格本身。
我在这里创建了一个问题的例子 - https://codepen.io/shaal/pen/qPvQWW
你可以看到,由于额外的包装,'sidebar'元素没有分配到我想要的区域。
HTML
Statement1 VALUE1
Statement1 VALUE2
Statement2 VALUE3
Statement2 VALUE4
.container {
display: grid;
grid-gap: 5px;
grid-template-areas: "header header header" "sidebar content content" "sidebar content content" "footer footer footer";
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.content {
grid-area: content;
height: 180px;
}
.footer {
grid-area: footer;
}
答案 0 :(得分:1)
如果使用unwrap jQuery函数删除这个div对你来说不是问题我会用它。
$(".sidebar").unwrap(".cms-annoying-wrapper");
否则在普通JS中: https://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/
答案 1 :(得分:1)
Grid Layout Module Level 2 - Subgrids are supposed to solve this problem.
In the meantime, there is a workaround (currently only working in firefox):
From Caniuse:
display: contents
causes an element's children to appear as if they were direct children of the element's parent, ignoring the element itself. This can be useful when a wrapper element should be ignored when using CSS grid or similar layout techniques.
So in your scenario you could simply add the rule:
.cms-annoying-wrapper {
display: contents;
}
Open the following snippet on Firefox:
body {
margin: 10px;
text-align: center;
width: 580px;
}
.cms-annoying-wrapper {
display: contents;
}
.container {
display: grid;
grid-gap: 5px;
grid-template-areas:
"header header header"
"sidebar content content"
"sidebar content content"
"footer footer footer";
}
.item {
color: white;
padding: 1.5em 0;
font-size: 2em;
}
.header {
background: #0d6;
}
.sidebar {
background: #f00;
}
.content {
background: #d60;
}
.footer {
background: #60d;
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.content {
grid-area: content;
height: 180px;
}
.footer {
grid-area: footer;
}
<h1>CSS GRID</h1>
<div class="container">
<div class="item header">Header</div>
<div class="cms-annoying-wrapper">
<div class="item sidebar">Sidebar</div>
<div class="item content">Content</div>
</div>
<div class="item footer">Footer</div>
</div>