简体   繁体   English

如何在同一元素上同时设置背景色和不同的文本颜色

[英]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: 笔记:

  • Instead of 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. 有时这些列表项可能大于链接本身。
  • I did not use a comma to combine li:hover and li:hover a . 我没有使用逗号来组合li:hoverli: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; }

You can do this: 你可以这样做:

First you make the background on the li, second you make the color of text 首先,您在li上制作背景,其次,您在制作文字颜色

CSS 的CSS

li:hover, li:hover a {
    background: #60266f;
     color: #fff;
}

DEMO HERE 此处演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM