<分区>
<分区>
下面的代码在 .current 和 .done 的 first-child 之前附加内容
.current:first-child::before {
content: 'Current ';
color: blue
}
.done:first-child::before {
content: 'Done ';
color: red
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<ul>
<li class="current">The first li.</li>
<li class="done">The second li.</li>
<li class="done">The third li.</li>
</ul>
</body>
</html>
我无法理解为什么内容“Done”没有附加在“The second li”之前,即使它是 .done 的第一个 child (.done:first-child::before)
最佳答案
使用:nth-child(n)
了解一下: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
在你的情况下,你只需要第一个,所以使用 nth-child(2)
.current:first-child::before {
content: 'Current ';
color: blue
}
.done:nth-child(2)::before {
content: 'Done ';
color: red
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<ul>
<li class="current">The first li.</li>
<li class="done">The second li.</li>
<li class="done">The third li.</li>
</ul>
</body>
</html>
这也适用于多个类 .current
或 .red
存在的情况。
.current > .current::before {
content: 'Current ';
color: blue
}
.done > .done::before {
content: 'Done ';
color: red
}
ul li:not(.done):first-child::before {
content: 'Current ';
color: blue;
}
ul li:not(.done) + .done::before {
content: 'Done';
color: red;
}
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<ul>
<li class="current">The first li.</li>
<li class="current">The first li.</li>
<li class="current">The first li.</li>
<li class="done">The second li.</li>
<li class="done">The third li.</li>
<li class="done">The third li.</li>
<li class="done">The third li.</li>
</ul>
</body>
</html>
关于HTML :first-child not giving desire result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50740099/