Open In App

How to Change the Item Color of List on Hover ?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In CSS, we can customize the interaction with the list element by changing the color of the list item on hover. We can also apply the different colors to each item using the :hover pseudo class in CSS.

Approach: Using the :hover Pseudo-class

In this approach, we are using the :hover pseudo-class in CSS to change the color and add bold styling to list items when they are hovered over.

Syntax:

li:hover {
color: red;
font-weight: bold;
}

Example 1: The below example uses the :hover Pseudo-class to change the item color of the list on hover.

HTML
<!DOCTYPE html>
<html>
  
<head>
    <title>Example 1</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        li {
            margin-bottom: 5px;
            transition: color 0.3s;
        }

        li:hover {
            color: green;
            font-weight: bold;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h3>Using :hover Pseudo-class</h3>
    <ul>
        <li>1. HTML</li>
        <li>2. CSS</li>
        <li>3. JavaScript</li>
        <li>4. Python</li>
    </ul>
</body>

</html>

Output:

fosiGIF

Example 2: The below example uses the :hover Pseudo-class with nth-child() selector to set different text colors for all list items.

HTML
<!DOCTYPE html>
<html>
  
<head>
    <title>Example 2</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }

        ul {
            list-style: none;
            padding: 0;
        }

        li {
            margin-bottom: 5px;
            transition: color 0.3s;
        }

        li:hover {
            cursor: pointer;
        }

        li:nth-child(1):hover {
            color: red;
            font-weight: bold;
        }

        li:nth-child(2):hover {
            color: blue;
            font-weight: bold;
        }

        li:nth-child(3):hover {
            color: green;
            font-weight: bold;
        }

        li:nth-child(4):hover {
            color: orange;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <h3>
        Using :hover Pseudo-class with
        nth-child() Selector
    </h3>
    <ul>
        <li>1. HTML</li>
        <li>2. CSS</li>
        <li>3. JavaScript</li>
        <li>4. Python</li>
    </ul>
</body>

</html>

Output:

fosiGIF



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads