【问题标题】:Getting hover selector to work on anchor containing other elements让悬停选择器在包含其他元素的锚点上工作
【发布时间】:2018-04-26 13:28:00
【问题描述】:

使用 html 5,我有一个包含块元素(例如 p 元素)的锚元素。我希望 p 元素中的文本在悬停时发生变化——它们不会。

p {
  color: #222222;
}

a:link {
  color: inherit;
  text-decoration: none;
}

a:visited {
  color: inherit;
  text-decoration: none;
}

a:hover {
  color: red !important;
  text-decoration: none;
}
<p><a href="test.htm">This changes color on hover</a>.</p>
<a href="test.htm">
  <p>This doesn't change color on hover.</p>
</a>

在我的例子中,锚元素中有很多元素,我无法更改这些元素的 CSS 样式(例如,我无法更改 p 元素的悬停选择器)。

谢谢!

【问题讨论】:

  • 尝试给需要自定义悬停动作的p元素添加一个指定的id。
  • 我不确定我是否理解你的问题,但你不能有这个吗? p:悬停{颜色:红色!重要;文字装饰:无; }

标签: css css-selectors hover


【解决方案1】:

p 不会从 a 标记周围继承悬停颜色,因为它有自己的 color 参数(感谢 @BoltClock)。但是你可以使用a:hover, a:hover p { ... } 作为选择器来得到你想要的:

p {
  color: #222222;
}

a:link {
  color: inherit;
  text-decoration: none;
}

a:visited {
  color: inherit;
  text-decoration: none;
}

a:hover,
a:hover p
{
  color: red !important;
  text-decoration: none;
}
<p><a href="test.htm">This changes color on hover</a>.</p>
<a href="test.htm">
  <p>This also changes color on hover.</p>
</a>

【讨论】:

  • 还是错了。规范中没有禁止从内联祖先继承的块元素。 p 没有继承,因为它有一个 color: #222222 声明应用于它,就这么简单。
  • @BoltClock 你是对的。由于我仍然提供了一个有效的代码解决方案并且不想删除它,我根据您的评论更改了我的答案文本。
  • 完美,约翰内斯!
【解决方案2】:

试试这个,这将改变锚元素内所有 p 元素的悬停选择器

p {
    color: #222222;
}

a:link {
    color: inherit;
    text-decoration: none;
}

a:visited {
    color: inherit;
    text-decoration: none;
}

a:hover {
    color: red !important;
    text-decoration: none;
}
a p:hover{
  color: red;
}
<p><a href="test.htm">This changes color on hover</a>.</p>
<a href="test.htm"><p>This doesn't change color on hover.</p></a>

【讨论】:

    猜你喜欢
    • 2015-04-20
    • 2012-07-15
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多