3

I want to show the value of an element's z-index in pseudo element inside of it by pure css.

To achieve that I decided to use CSS variables. But the problem is that z-index is a number, but content is a string. How can I cast a value?

In following example: if p uses z-index: var(--z) it is shown over red div with z-index: 8. I want p to use z-index and to show after at the same time. How can I do it?

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Qwertiy
  • 19,681
  • 15
  • 61
  • 128

1 Answers1

2

Found an interesting hack:

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

The whole code:

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>
Qwertiy
  • 19,681
  • 15
  • 61
  • 128