首页 > 解决方案 > HTML:第一个孩子没有给出期望的结果

问题描述

下面的代码将内容附加在 .current 和 .done 的第一个孩子之前

.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>

我无法理解为什么内容“完成”没有附加在“第二个 li”之前,即使它是 .done (.done:first-child::before) 的第一个孩子

标签: htmlcsscss-selectorspseudo-element

解决方案


使用: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>


推荐阅读