【问题标题】:Unable to change color of nested link无法更改嵌套链接的颜色
【发布时间】:2020-10-06 03:31:37
【问题描述】:

我希望能够在每个页面上将我的一个链接标记为活动类,并将其上的文本变为黑色并带有下划线。我在 chrome 上运行代码,我已经通过实时服务器和原生的 chrome 进行了尝试。

我无法从逻辑上弄清楚为什么它不允许我以这种方式更改颜色。

/* Example CSS */

.nav li a {
  margin-left: 0px;
  margin-right: 10px;
  text-decoration: none;
  color: brown;
}

.active {
  text-decoration: underline;
}

.active a {
  color: black;
}

.nav li:hover {
  text-decoration: underline;
}
<!-- example.html-->

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="estyles.css">
</head>

<body>
  <ul class="nav">
    <li class="active"><a href="example.html">Example</a>       </li>
    <li><a href="example1.html">Example1</a></li>
  </ul>
</body>

【问题讨论】:

标签: html css text hyperlink


【解决方案1】:

你可以试试这个:

.active a {
  color: black !important;
}

【讨论】:

  • 不,推荐使用!important 实际上从来都不是最好的解决方案
  • 我不能不同意你的观点,但它仍然是一个解决方案
  • 感谢您的帮助,非常感谢 - 我不知道您可以这样声明重要性:)
【解决方案2】:

正如我在评论中提到的,问题在于选择器的特殊性。将您的 .active a 选择器更改为 li.active a

/* Example CSS */

.nav li a {
  margin-left: 0px;
  margin-right: 10px;
  text-decoration: none;
  color: brown;
}

.active {
  text-decoration: underline;
}

li.active a {
  color: black;
}

.nav li:hover {
  text-decoration: underline;
}
<ul class="nav">
  <li class="active"><a href="example.html">Example</a> </li>
  <li><a href="example1.html">Example1</a></li>
</ul>

【讨论】:

  • 问题已解决,感谢您抽出宝贵时间解释最佳做法
【解决方案3】:

另一种方法是使用子选择器 (>) 和属性选择器 .active &gt; a[href]

.nav li a {
  margin-left: 0px;
  margin-right: 10px;
  text-decoration: none;
  color: brown;
}

.active {
  text-decoration: underline;
}

.active > a[href] {
  color: black;
}

.nav li:hover {
  text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="estyles.css">
</head>

<body>
  <ul class="nav">
    <li class="active"><a href="example.html">Example</a>       </li>
    <li><a href="example1.html">Example1</a></li>
  </ul>
</body>

【讨论】:

    猜你喜欢
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多