2017-03-01 3 views
1

純粋なCSSによって、の中の擬似要素の要素のz-indexの値を表示したいとします。css変数の型をキャストする方法は?

これを達成するために、私はCSS変数を使用することに決めました。しかし、問題は、z-indexは数字ですが、contentは文字列です。どのように私は価値をキャストすることができますか?

pz-index: var(--z)を使用する場合は、divz-index: 8と表示しています。 pz-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

見つかり面白いハック:

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>

関連する問題