To change the color when hovering in CSS, you will use the CSS selector called :hover.

The :hover is a CSS pseudo-class that will select the HTML element when the user hovers over with the mouse. The hover selector will work on almost all HTML elements.

Let’s use a button as an example to see how the hover selector works:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Website example</title>
  </head>
  <body>
    <style>
      button {
        padding: 15px 36px;
        font-size: 16px;
        color: white;
        background-color: red;
        border: none;
      }
    </style>

    <button>Button</button>
  </body>
</html>

In the above example, we have created a simple red button in an HTML file. To change the color of that button when hovering over it, we will add the hover selector and insert a new color for the button. For this one, we will set the color to dark red color:

button:hover {
        background-color: darkred;
      }

Try hovering over the button and see what will happen. It will change the color from red to dark red. When you hover away, it will go back to its original color.

Optionally, if you want to make the transition smoother, use the transition inside the button hover and set the value to 0.2s.

Like this:

button:hover {
        background-color: darkred;
        transition: 0.2s;
      }

Now if you hover over the button again, it will transit smoothly which looks way better than before.

And there you go! That is how you change the color in hovering in CSS with the help of the CSS selector named :hover.

I hope you find this guide helpful and happy coding!

Get my free e-book to prepare for the technical interview or start to Learn Full-Stack JavaScript