问题
I'm trying to understand and work my way through the css-grid grid-template-areas
option.
given this html
<div class="wrapper">
<div class="d">D</div>
<div class="b">B</div>
<div class="c">C</div>
<div class="a">A</div>
</div>
and this css
.wrapper {
grid-template-areas: "areaA areaB areaC areaD"
}
.A { grid-area: areaA; }
.B { grid-area: areaB; }
.C { grid-area: areaC; }
.D { grid-area: areaD; }
I get the (expected) following result
A B C D
now if I add a media query, and wanted to hide column B, C and D
@media (min-width: 500px) {
.wrapper {
grid-template-areas: "areaA";
}
.B {
display: none;
}
.C {
display: none;
}
.D {
display: none;
}
}
this also works :
A
now, I then removed the display:none
entries, hoping that because there was no mention of the elements in grid-template-areas
that they would not show. I was wrong ;)
Is it possible to specify just using css-grid that elements not specified are hidden by default ? I can't seem to find anything that mentions this
回答1:
The grid-template-areas property cannot hide grid items. It is designed to create grid areas.
But your media query can still be very simple.
This is all you need:
@media (max-width: 500px) {
section:not(.a) { display: none; }
}
jsFiddle demo
article {
display: grid;
grid-template-areas: "areaA areaB areaC areaD";
}
@media (max-width: 500px) {
section:not(.a) { display: none; }
}
.a { grid-area: areaA; }
.b { grid-area: areaB; }
.c { grid-area: areaC; }
.d { grid-area: areaD; }
/* non-essential demo styles */
section {
height: 50px;
width: 75px;
background-color: lightgreen;
border: 1px solid #ccc;
display: flex;
justify-content: center;
align-items: center;
font-size: 1.2em;
}
<article>
<section class="d">D</section>
<section class="b">B</section>
<section class="c">C</section>
<section class="a">A</section>
</article>
来源:https://stackoverflow.com/questions/48660366/hide-elements-not-specified-in-grid-template-areas