如何转换css变量的类型?

时间:2017-03-01 13:22:10

标签: css css3 css-variables

我想通过纯css 在中的伪元素中显示元素的z-index的值。

为了实现这一点,我决定使用CSS变量。但问题是z-index是一个数字,但content是一个字符串。我怎样才能施展价值?

在以下示例中:如果p使用z-index: var(--z),则会显示红色div z-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.

1 个答案:

答案 0 :(得分:1)

发现一个有趣的黑客:

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>