Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

css - grid-area does not seem to work with the attr function, is this by design?

The following works:

Note how I'm even using content: attr(class) to avoid having to type out the labels. Neat!

section {
  outline: 1px solid red;
  display: grid;
  grid-gap: 10px;
  grid-template-areas: 
"a1 a1 a1 a1" 
"a2 a2 a3 a3" 
"a2 a2 a4 a5" 
"a6 a6 a6 a6" 
"a7 a8 a9 a9" 
"a7 a0 a0 a0";
}
.a1 { grid-area: a1; }
.a2 { grid-area: a2; }
.a3 { grid-area: a3; }
.a4 { grid-area: a4; }
.a5 { grid-area: a5; }
.a6 { grid-area: a6; }
.a7 { grid-area: a7; }
.a8 { grid-area: a8; }
.a9 { grid-area: a9; }
.a0 { grid-area: a0; }
div {
  display: flex;
  outline: 1px dotted green;
}
div:before {
  margin: auto;
  content: attr(class);
}
<section>
<div class="a1"></div>
<div class="a2"></div>
<div class="a3"></div>
<div class="a4"></div>
<div class="a5"></div>
<div class="a6"></div>
<div class="a7"></div>
<div class="a8"></div>
<div class="a9"></div>
<div class="a0"></div>
</section>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes it's by design as attr() is acutally only suppored with content. As defined in the current specification it's a value for content.

You can also read in MDN:

Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse.

So it may work with other properties but this is still in draft mode


An alternative is to consider CSS variables where you will almost have the same thing to write but it will not work with content because it's not a string. For the content you can replace this with counters:

section {
  outline: 1px solid red;
  display: grid;
  grid-gap: 10px;
  grid-template-areas: 
"a1 a1 a1 a1" 
"a2 a2 a3 a3" 
"a2 a2 a4 a5" 
"a6 a6 a6 a6" 
"a7 a8 a9 a9" 
"a7 a0 a0 a0";
    
  counter-reset:g;
}

div {
  display: flex;
  grid-area: var(--c);
  outline: 1px dotted green;
}
div:before {
  margin: auto;
  counter-increment: g;
  content: "a" counter(g);
}
<section>
<div style="--c:a1"></div>
<div style="--c:a2"></div>
<div style="--c:a3"></div>
<div style="--c:a4"></div>
<div style="--c:a5"></div>
<div style="--c:a6"></div>
<div style="--c:a7"></div>
<div style="--c:a8"></div>
<div style="--c:a9"></div>
<div style="--c:a0"></div>
</section>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...