如何转换 css 变量的类型?

How to cast type of css variable?

我想通过 pure css.

在其内部的伪元素中显示元素 z-index 的值

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

在下面的示例中:如果 p 使用 z-index: var(--z),则显示为红色 divz-index: 8。我希望 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: Same question in Russian.

发现一个有趣的技巧:

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>