Open In App

How to change background color when hover over li elements using CSS ?

Last Updated : 20 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to change the background color of li (list item) on hover using CSS.

The hover effect may be used to indicate interactivity or might just be there for aesthetic purposes, like highlighting different items in case of a list. Hover event can be styled using the :hover pseudo-class, and activates generally when the user’s cursor is over the element.

Syntax: To style the li element on hover:

li:hover{
    property-name: value;
}

Approach: As we want to change the background color of li elements on hovering over them, we will add a background-color property with a color that we want to change to on hover, in the li:hover selector. This is shown in the below example where the background-color will change to cyan on hover.

Example 1: In the code below, we have created an unordered list with 2 list items. The color of the list items changes on hovering over them.   

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Hover styling on li</title>
    <style>
        li:hover{
            background-color:cyan;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <p>Let's see the hover effect on li element</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
    </ul>
</body>
  
</html>


Explanation: We have used the li: hover selector for styling list items on hover. Under this selector, we have specified the property i.e. background-color : cyan on hovering over a list item. Alternatively, a class can be used to style specific list items, with different properties, on hover (as shown in the 2nd code example). 

Output: 

code 1 output

Example 2: In this example, we have created a class that contains the different CSS properties & utilize it to style the list with a custom option.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Hover styling on li</title>
    <style>
        .special:hover{
            cursor: pointer;
            background-color: burlywood;
        }
    </style>
</head>
  
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <p>Let's see the hover effect on some li elements</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li class="special">Item Special</li>
        <li>Item 3</li>
        <li class="special">Item Special 2</li>
    </ul>
</body>
</html>


Explanation: Here, the color of list items with “special” class changes on hovering over them, and the cursor changes to the pointer.  We can change the background-color of li on hover. Similarly, other properties could also be specified under the CSS :hover selector, and can be used for other tags, depending on the requirements.

Output:

code 2 output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads