2017-03-01 114 views
1

我想通過pure css在其中的僞元素中顯示元素的值z-index如何投射css變量的類型?

爲了實現這一點,我決定使用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.

回答

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>