问题
I really love the simplicity and ease of manipulation of grid-template-areas
, but is there an easier way/shortcut to indicate an area spans multiple columns (say 12) — within the template?
This starts to get pretty gross when you have 12 columns...
.wrapper{
display: grid;
grid-template-areas:
"nav nav cont cont cont cont cont cont cont cont cont cont";
@media all and (max-width: 839px){
grid-template-areas:
"nav nav cont cont cont cont";
}
}
回答1:
You can combine it with grid-template-columns
like this:
.wrapper{
display: grid;
grid-template-areas:
"nav cont";
grid-template-columns:2fr 10fr;
@media all and (max-width: 839px){
grid-template-areas:
"nav cont";
grid-template-columns:1fr 4fr;
}
}
Example:
.wrapper {
display: grid;
grid-template-areas: "nav cont";
grid-template-columns: 2fr 10fr;
}
.nav {
grid-area: nav;
height: 100px;
background: red;
}
.cont {
grid-area: cont;
height: 100px;
background: blue;
}
@media all and (max-width: 839px) {
.wrapper {
grid-template-areas: "nav cont";
grid-template-columns: 1fr 4fr;
}
}
<div class="wrapper">
<div class="nav">
</div>
<div class="cont">
</div>
</div>
回答2:
Named areas are just shortcuts for named lines, and so you can use either. For example, your 12-column code can instead be written as:
.wrapper{
display: grid;
grid-template-columns: [nav-start] repeat(2, auto) [nav-end cont-start] repeat(10, auto) [cont-end];
}
The -start
and -end
line names define named areas in the same way that grid-template-areas
does, and are sometimes more convenient to use.
(That said, I recommend usually doing what @temani-afif said, and instead just having two meaningful columns, using fr
units to designate their relative sizes. Literal 12-column grids are an artifact of the old limitations that grid systems had to work in. But on the other hand, using actual multiple columns is sometimes clearer, especially if you're using gaps between the columns. Do whatever works best for you.)
来源:https://stackoverflow.com/questions/52359428/easier-way-use-css-grid-template-areas-to-span-multiple-columns