Reputation: 199234
I'm learning CSS grid and while trying to do my layout and use semantic html at the same time I run into some problems
https://codepen.io/oscarryz/pen/oNNBKyd
So basically I'm doing grid as 3x3 with empty space on the left and right and the content in the middle
.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>
As can be seen in the codepen above, this is not working. If I remove the semantic tags it works, obviously there must be a correct way of doing this
Upvotes: 2
Views: 4213
Reputation: 26160
Grid templates are for direct descendants.
The semantic elements should be referenced by tagname, not class:
/* 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;
}
Corrected codepen here: https://codepen.io/c_bergh/pen/eYYvOmG
Upvotes: 3
Reputation: 723708
You've assigned grid areas to your non-semantic elements in your CSS. That's why the semantic elements are interfering with your grid — because they ended up not participating in your grid at all. If you had started out with the non-semantic structure, then migrated to semantic elements, this may have been a step you missed.
Assigning the grid areas to your semantic elements allows you to remove the non-semantic ones instead, completing this migration:
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>
Upvotes: 2