Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to add a hover effect

Short answer

The :hover pseudo-class applies while the pointer is over the element:

<style>
  .btn { padding: 8px 18px; border: none; border-radius: 8px; background: royalblue; color: white; }
  .btn:hover { background: navy; }
</style>
 
<button class="btn">Hover over me</button>

Smoothly

Without transition the color jumps. Add it to the normal state, not to :hover, so the effect is smooth both on the way in and on the way out:

<style>
  .link { color: teal; text-decoration-color: transparent; transition: text-decoration-color 0.3s, color 0.3s; }
  .link:hover { color: darkslategray; text-decoration-color: currentColor; }
</style>
 
<a class="link" href="https://example.com">Read more</a>

Hovering the parent

The effect can change child elements — for example, show a button when you hover the card:

<style>
  .card { padding: 12px; background: whitesmoke; }
  .card button { opacity: 0; transition: opacity 0.2s; }
  .card:hover button, .card:focus-within button { opacity: 1; }
</style>
 
<div class="card">Photo of the day <button>Save</button></div>

Common mistake

Phones have no hover: the effect fires on tap and gets "stuck". Do not hide important things behind :hover — as in the last example, add :focus-within or always show the button. And for keyboard users repeat the effect with :focus-visible.

Functions used in this recipe

  • :hover — Matches an element while the mouse pointer is over it.
  • :focus-visible — Matches a focused element when the browser decides the focus should be visible — usually after keyboard navigation.
  • transition — Animates the change of a property from the old value to the new one.
  • cursor — The look of the mouse pointer over the element.

Thanks for reading!

Donate to the site — we work hard for you.