CSS Hover
This page explains and demonstrates how to use the CSS hover
pseudo-class to achieve visual effects when the user hovers the cursor over an element. This method is a quick and easy way to provide an effect without needing to use the JavaScript onMouseover
event handler.
Cascading Style Sheets (CSS) provides pseudo-classes that enable you to change the style HTML elements upon user interaction (such as hovering over or clicking an element). These are often used with the CSS text-decoration
and color
properties to change the text color and/or remove/add an underline under the text.
While more advanced functionality can be provided using JavaScript (i.e. using the aforementioned onMouseover
event handler), styles can be changed upon a hover over simply by using the CSS pseudo-classes listed on this page.
Example
In this example, whenever the user hovers over any link within the <div>
element with a class of cool-effects
the underline will be removed, the color will change, and the font will become bold. You could add any relevant CSS property to the hover effect, however, be mindful of usability — hover over effects can be quite annoying if abused!
Source Code | Result |
---|---|
Non Link Hover
Although the hover
pseudo-class is often used with links, it is not limited to just links — it can be used on any HTML element. For example, you could use it on normal paragraph text, like this:
Source Code | Result |
---|---|
Normal paragraph text... |
CSS Hover & Click
You can also specify properties for when the user clicks the link. This is achieved by using the active
pseudo-class.
Example:
Source Code | Result |
---|---|
Normal paragraph text... |
Other Pseudo-Classes
Other pseudo-classes include link
(for unvisited links), visited
(for visited links), and focus
(for any element that currently has focus).
Example:
Source Code | Result |
---|---|
A link to this page (i.e. already visited) |
Ordering Pseudo-Classes
Careful attention needs to be paid to the order in which you place your pseudo-classes. If you use :link
, :visited
, :hover
, and active
pseudo-classes, you should place them in that order. Otherwise the cascading effect of one pseudo-class may "hide" any effect that you're trying to achieve with a previous pseudo-class. For example, if you place :hover
before the :link
pseudo-class, the :link
pseudo-class will override your :hover
pseudo-class.
So again, as long as you place your pseudo-classes in the following order, you will be fine:
a:link
a:visited
a:hover
a:active
How Not To Do a Hover Over Effect
OK, let's have a little fun and go way over the top with our CSS hover over effect. Let's add properties that really screw up the text and generally make things really difficult for the user.
You could say this is how not to do a hover-over effect (mind you, it doesn't look that bad — I've seen worse!)
Source Code | Result |
---|---|
So I found these really cool HTML templates that I thought you might be interested in. |