悬停在li上时更改文本颜色 [英] Change text color when hovered over li

查看:259
本文介绍了悬停在li上时更改文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<li>元素悬停在上方时,我想更改链接的文本颜色.现在我有

I want to change the text color of links when an <li> element is hovered over. Right now I have

#nav li a:hover {
  margin-left: -10px;
  padding-left: 10px;
  background-color: #13118C;
  color: white; 
  font-weight: bold;
  width: 100%;
}

#nav ul li:hover {
  margin-left: -10px;
  padding-left: 10px;
  background-color: #13118C;
  color: white; 
  font-weight: bold;
  width: 100%;
}

但是,仅当链接本身悬停在上方时,这才会更改文本颜色.如果鼠标稍微位于链接的右侧,则背景会更改,但文本不会更改.我希望它位于链接右边的鼠标在功能上与在链接本身上的鼠标相同.当背景改变时,有没有办法改变文字颜色?

However, this only changes the text color when the link itself is hovered over. If the mouse is slightly to the right of the link, the background changes but the text does not. I'd like it so that the mouse being to the right of the link is functionally the same as it being on the link itself. Is there a way to have the text color change when the background does?

推荐答案

然后确保a从其父级继承其颜色:

Then ensure that either the a inherits its colour from its parent:

li:hover a {
    color: inherit;
}

或指定一个选择器以将相同的颜色显式地应用于a元素:

Or specify a selector to explicitly apply the same colour to the a element:

#nav ul li:hover,
#nav ul li:hover a {
  margin-left: -10px;
  padding-left: 10px;
  background-color: #13118C;
  color: white; 
  font-weight: bold;
  width: 100%;
}

当然,您还可以使用以下方法使a填充li元素:

You could, of course, also make the a fill the li element, using:

#nav ul li a {
    display: block;
}

如果您为li指定了高度,则使用相同的高度(使用以前的display: block规则),a也将在li内垂直居中,例如:

If you specify a height for the li, then use that same height (with the previous display: block rule) the a will be vertically-centred within the li as well, for example:

#nav ul li {
    height: 2em; /* or whatever, adjust to taste... */
}
#nav ul li a {
    display: block;
    line-height: 2em;
}

尽管lipadding不会包含在指定的高度内(它将是元素的高度,加上填充加上边框宽度),所以将有一个空白-a周围的空格,除非您指定(对于兼容的浏览器)box-sizing: border-box;在指定的高度包含borderpadding.

Though the padding of the li won't be included within the specified height (it'll be the height of the element, plus the padding plus the border-width), so there'll be an empty-space around the a, unless you specify (for compliant browsers) box-sizing: border-box; to include the border and padding in the specified height.

这篇关于悬停在li上时更改文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆