How to Use Hover in CSS: Simple Guide with Examples
Use the
:hover pseudo-class in CSS to apply styles when the mouse pointer is over an element. Write a selector followed by :hover and define the styles inside curly braces to change appearance on hover.Syntax
The :hover pseudo-class targets an element when the mouse pointer is over it. You write it after the element selector, then add the styles you want to change inside curly braces.
selector:hover— selects the element on hover{ property: value; }— styles applied during hover
css
selector:hover {
property: value;
}Example
This example changes the background color and text color of a button when you hover over it with the mouse.
css
button {
background-color: lightblue;
color: black;
padding: 10px 20px;
border: none;
cursor: pointer;
font-size: 1rem;
transition: background-color 0.3s ease, color 0.3s ease;
}
button:hover {
background-color: darkblue;
color: white;
}Output
A light blue button with black text that changes to dark blue background and white text when hovered.
Common Pitfalls
Some common mistakes when using :hover include:
- Not adding
cursor: pointer;for clickable elements, so users don't see the pointer change. - Forgetting to add
transitionfor smooth style changes. - Using
:hoveron elements that are hard to hover on small screens or touch devices. - Trying to use
:hoveron non-interactive elements without clear feedback.
css
/* Wrong: No cursor change and no transition */ button:hover { background-color: red; } /* Right: Add cursor and transition for better UX */ button { cursor: pointer; transition: background-color 0.3s ease; } button:hover { background-color: red; }
Quick Reference
Remember these tips when using :hover:
- Use
:hoverto change styles on mouse over. - Add
cursor: pointer;for clickable items. - Use
transitionfor smooth effects. - Test on different devices; hover doesn't work on touch screens.
Key Takeaways
Use the :hover pseudo-class to style elements when the mouse is over them.
Add cursor: pointer to show clickable elements on hover.
Use transition for smooth style changes on hover.
:hover works only with mouse devices, not touch screens.
Test hover effects on different screen sizes for best user experience.