我想在其内部的pseudo元素中显示元素的 z-index
的值,由pure css 。
为了实现这一目标,我决定使用CSS变量。但是问题是z-index
是一个数字,但是content
是字符串。我如何施放价值?
在以下示例中:如果p
使用z-index: var(--z)
,则用z-index: 8
在红色div
上显示。我希望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:俄语中的同样问题。
找到一个有趣的黑客:
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>