我正在学习CSS网格,在尝试进行布局和使用语义html的同时,我遇到了一些问题
https://codepen.io/oscarryz/pen/oNNBKyd
所以基本上我把网格做成 3x3,左右有空白,内容在中间
.grid-container {
display: grid;
grid-template-columns: 1fr 40em 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-template-areas:
" . header . "
" . content . "
" . footer . ";
}
.header {
grid-area: header;
}
.content {
grid-area: content;
}
.footer {
grid-area: footer;
}
.header, .content, .footer {
border: 1px solid red;
}
<div class="grid-container">
<header>
<div class="header">header</div>
</header>
<main>
<div class="content">content</div>
</main>
<footer>
<div class="footer">footer</div>
</footer>
</div>
从上面的代码笔中可以看出,这是行不通的。如果我删除语义标签它就可以工作,显然必须有正确的方法来做到这一点
网格模板适用于直系后代。
语义元素应该由标签名引用,而不是类:
/* changed from .header, which is a _child_ of header */
header {
grid-area: header;
}
/* changed from .content, which is a _child_ of main */
main {
grid-area: content;
}
/* changed from .footer, which is a _child_ of footer */
footer {
grid-area: footer;
}
此处更正的代码笔:https://codepen.io/c_bergh/pen/eYYvOmG
你已经为CSS中的非语义元素分配了网格区域。这就是为什么语义元素会干扰你的网格——因为它们最终根本不参与你的网格。如果您从非语义结构开始,然后迁移到语义元素,这可能是您错过的步骤。
将网格区域分配给语义元素允许您删除非语义元素,从而完成此迁移:
html,
body,
.grid-container {
height: 100%;
margin: 0;
}
.grid-container * {
border: 1px solid red;
position: relative;
}
.grid-container {
display: grid;
grid-template-columns: 1fr 40em 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-template-areas:
" . header . "
" . content . "
" . footer . ";
}
header {
grid-area: header;
}
main {
grid-area: content;
}
footer {
grid-area: footer;
}
<div class="grid-container">
<header>header</header>
<main>content</main>
<footer>footer</footer>
</div>