如何施放CSS变量的类型



我想在其内部的pseudo元素中显示元素的 z-index的值,由pure css

为了实现这一目标,我决定使用CSS变量。但是问题是z-index是一个数字,但是content是字符串。我如何施放价值?

在以下示例中:如果p使用z-index: var(--z),则用z-index: 8在红色div上显示。我希望p使用z-index并同时显示after。我该怎么办?

p {
  position: relative;
  z-index: var(--z);
  background: silver;
}
p:after {
  content: var(--z);
  color: red;
}
div {
  background: red;
  z-index: 8;
}
/* just some styling and positioning stuff bellow */
body {
  margin: 0;
}
p {
  margin: 1em .5em;
  padding: 0 .5em 0 3.5em;
  line-height: 2em;
}
div {
  position: absolute;
  top: .5em;
  left: 1em;
  height: 6em;
  width: 2em;
}
<p style="--z: 9">
  I have correct z-index, but have no :after
</p>
<p style="--z: '9'">
  I have no z-index, but have :after
</p>
<div></div>

ps:俄语中的同样问题。

找到一个有趣的黑客:

p:after {
  counter-reset: z var(--z);
  content: counter(z);
}

整个代码:

p {
  position: relative;
  z-index: var(--z);
  background: silver;
}
p:after {
  content: var(--z);
  color: red;
}
p.solution:after {
  counter-reset: z var(--z);
  content: counter(z);
  color: red;
}
div {
  background: red;
  z-index: 8;
}
/* just some styling and positioning stuff bellow */
body {
  margin: 0;
}
p {
  margin: 1em .5em;
  padding: 0 .5em 0 3.5em;
  line-height: 2em;
}
div {
  position: absolute;
  top: .5em;
  left: 1em;
  height: 9em;
  width: 2em;
}
<p style="--z: 9">
  I have correct z-index, but have no :after
</p>
<p style="--z: '9'">
  I have no z-index, but have :after
</p>
<p class="solution" style="--z: 9">
  I have both z-index and :after
</p>
<div></div>

最新更新