HTML :first-child not giving desire result

标签 html css css-selectors pseudo-element

<分区>

下面的代码在 .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/

上一篇:javascript - JS点击事件监听器没有按预期触发功能

下一篇:html - 创建 slider 但无法将图像置于绝对 div 的中心

相关文章:

javascript - 表单级别的 Angularjs 指令,访问所有字段并检查验证

css Column/Grid-Layout : position or float. 还有其他选择吗?

html - 表格为行应用CSS

html - 具有内联样式的 CSS 伪类

javascript - 如何使命令在浏览器控制台中循环运行

jquery - Foundation sticky header 第一次滚动

html - Bootstrap block 表现不佳

html - 如何在中间垂直对齐图像和文本?

html - 我希望我的按钮具有与页面背景不同的固定封面背景

c# - 下拉复选框在 IE 8 兼容模式下无法正确滚动