html - 第 n 个 child 给错误的颜色上色

标签 html css css-selectors

<分区>

我正在尝试使用 nth-child(); 使每个 li 具有不同的颜色 这是我的 CSS:

header ul a:nth-child(1) {
    color: #8cf;
}
header ul a:nth-child(2) {
    color: #f8c;
}
header ul a:nth-child(3) {
    color: #8fc;
}
header ul a:nth-child(4) {
    color: #b9b;
}
header ul a:nth-child(5) {
    color: #c8c;
}

这是我的 html:

  <body>
<div id="main">
<header>
  <nav>
    <ul>
      <li><a href="index.html">Home</a></li>
      <li><a href="blog.html">Blog</a></li>
      <li><a href="forums.html">Forums</a></li>
      <li id="iamhere"><a href="instruction.html">Instruction</a></li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
  </nav>
</header>

虽然我在任何地方都没有提到紫色,但一切都是紫色的。

最佳答案

您需要在 li 标签上使用 nth-child(),您的 a 标签没有任何兄弟。紫色是浏览器已访问链接的默认颜色。

header ul li:nth-child(1) a {
  color: #8cf;
}
header ul li:nth-child(2) a {
  color: #f8c;
}
header ul li:nth-child(3) a {
  color: #8fc;
}
header ul li:nth-child(4) a {
  color: #b9b;
}
header ul li:nth-child(5) a {
  color: #c8c;
}
<div id="main">
  <header>
    <nav>
      <ul>
        <li><a href="index.html">Home</a>
        </li>
        <li><a href="blog.html">Blog</a>
        </li>
        <li><a href="forums.html">Forums</a>
        </li>
        <li id="iamhere"><a href="instruction.html">Instruction</a>
        </li>
        <li><a href="contact.html">Contact</a>
        </li>
      </ul>
    </nav>
  </header>

关于html - 第 n 个 child 给错误的颜色上色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195940/

相关文章:

html - CSS 子选择器 - 在两个不同的 div 中操作相同的 div 类

python - 为什么这段代码会得到 this 'str' object has no attribute 'get_match_routes' 错误?

javascript - 在 html 中调用类的简单问题

twitter-bootstrap - 当分辨率低于 767 时将 Bootstrap 列居中

javascript - 从另一个 div 的底部/后面滚动显示固定部分

html - CSS 选择器 :nth-child(even|odd) vs :nth-child(int)

html - 网站四周都是黑色空间

html - 如何固定元素 p 的大小

html - 在 birdseye weebly 主题上停止固定标题并使 Logo 更大

html - 第 n 个 child 没有针对正确的元素?