I want on pure css to show the value of z-index and the element in its pseudo-element.

I decided to use a css variable for this ( support by browsers ). But the problem is that for z-index there must be a number in it, and for content - a string. How to type?

In the following example, in the case when the z-index triggered, the silver p shown over the red div a. If content triggered, then a number is displayed at the end of the paragraph. How to make, that simultaneously worked both z-index , and content ?

 p { position: relative; z-index: var(--z); background: silver; } p:after { content: var(--z); color: red; } div { background: red; z-index: 8; } /* дополнительная стилизация и размеры */ 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"> У меня правильный z-index, но нет :after </p> <p style="--z: '9'"> У меня нет z-index, но есть :after </p> <div></div> 

PS: This question is in English.

  • association: stackoverflow.com/q/42532945/4928642 - Qwertiy
  • one
    This is NOT a self - replying question, we answer :) - Qwertiy
  • @mJeevas, the question was originally mine, on both sites. Like the answer. But on SO they found some older question that came down to the same and closed mine as a duplicate: ( - Qwertiy
  • @Qwertiy the solution to this question is exactly the same solution - through the counters, apparently because they closed it - Sasha Omelchenko
  • @SashaOmelchenko, in general, yes - the problem and the solution are the same (however, this solution is only for numbers). But I like my example more - it seems to be fairly clear and without scripts, unlike that question. - Qwertiy

1 answer 1

Found an interesting hack:

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

Complete 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; } /* дополнительная стилизация и размеры */ 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"> У меня правильный z-index, но нет :after </p> <p style="--z: '9'"> У меня нет z-index, но есть :after </p> <p class="solution" style="--z: 9"> А у меня есть всё!!! </p> <div></div> 

Should work in Firefox 31+, Chrome 49+ (Opera 36+), Safari 9.3+.
IE and Edge 14 are forested, Edge 15 is unclear.

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin