[英]How to set both a background colour and a different text color on the same element
I have an un-ordered list with link tags inside and I would like to change the color of the background and the text when the list is hovered by the users mouse. 我有一个内部有链接标签的无序列表,当用户将鼠标悬停在列表上时,我想更改背景和文本的颜色。
Here is my html: 这是我的html:
<ul>
<li><a href="">text</a></li>
<li><a href="">text</a></li>
<li><a href="">text</a></li>
</ul>
Here is my css: 这是我的CSS:
li:hover {
background-color: #60266f;
}
I can't seem to work out how to apply a text color to the li tags as well as a background color. 我似乎无法弄清楚如何将文本颜色以及背景颜色应用于li标签。
Can anyone explain where I may be going wrong? 谁能解释我可能会出问题的地方?
The browser is setting a color to a:hover, and it would override any color style you put in li:hover
浏览器正在将颜色设置为a:hover,它将覆盖您放置在
li:hover
任何颜色样式
You can add a style to it using CSS like this: 您可以使用CSS向其中添加样式,如下所示:
li:hover {
background-color: #60266f;
}
li:hover a {
color: #f00;
}
You can see it in this JS fiddle: https://jsfiddle.net/eytbzuq8/ 您可以在此JS小提琴中看到它: https : //jsfiddle.net/eytbzuq8/
There's a difference between background-color:
(or background:
) and color
. background-color:
或background:
和color
之间有区别。
That last one is the one you're looking for. 最后一个是您要寻找的那个。
Details: 细节:
li:hover {background: red;}
to set the background of the list-item. li:hover {background: red;}
设置列表项的背景。 li:hover a {color: yellow;}
to set the text-color of the a inside the list item. li:hover a {color: yellow;}
以设置列表项内a的文本颜色。 Notes: 笔记:
li a:hover
I used li:hover a
because this will cause the text color to change if you only hover the list item itself. li a:hover
我使用了li:hover a
因为如果您仅悬停列表项本身,这将导致文本颜色改变。 Sometimes these list items might be bigger than the link itself. li:hover
and li:hover a
. li:hover
和li:hover a
。 This makes it possible to change text outside the link to another color than the link itself. Example: 例:
li:hover {color: red; background: cyan;} li:hover a {color: yellow; background: red;}
<ul> <li><a href="#Link1">Link 1</a> </li> <li><a href="#Link2">Link 2</a> with some text outside the a-tag. </li> </ul>
li a{ display:inline-block; color:red; background:black }
li a:hover{ color:white; background:green; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.