简体   繁体   中英

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:

<ul>
<li><a href="">text</a></li>
<li><a href="">text</a></li>
<li><a href="">text</a></li>
</ul>

Here is my 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.

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

You can add a style to it using CSS like this:

li:hover {
    background-color: #60266f;
}
li:hover a {  
    color: #f00;
}

You can see it in this JS fiddle: https://jsfiddle.net/eytbzuq8/

There's a difference between background-color: (or background: ) and 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 a {color: yellow;} to set the text-color of the a inside the list item.

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. 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 . 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

CSS

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

DEMO HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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