Web Design Tips: CSS Mouseover Effects
How to create CSS mouseover effects
If you don’t know what you’re looking for, the CSS mouseover effect can be difficult to find since it is implemented by the :hover pseudo-class. A pseudo-class is an extender that can be added to any class or element in your CSS, but adds certain conditions to define when or where that style is applied. Specific to this case, styles defined with the :hover pseudo-class are only applied when the mouse is positioned over the class or element that :hover is attached to.
The best way to learn the intricacies of CSS is by example, so let’s jump right in with something basic. If you wanted to apply the style of red text to all elements on your web page, you would place the following line in your CSS:
p { color: red; }
If instead you wanted elements to have the red text style whenever a user places their mouse cursor over them, you would simply add the :hover pseudo-class to the above example, which defines that this style is only applied to the elements on mouseover. That would look like this:
p:hover { color: red; }
Pretty simple right? You can do the exact same thing for CSS styles that are applied to a class. The first line below is an example of making all page elements with the “redtext” class have red text, and the second line is the same style but applied only when the user places their mouse over the element:
.redtext { color: red; }
.redtext:hover { color: red; }
When are CSS mouseover effects applied?
In the above two examples we apply the same style to both the standard and :hover cases, but that is in no way a requirement. For example, you could set the CSS mouseover style to green text, while setting the standard style red text. In that case, the standard style will be applied until the user places their mouse over the element, at which time the :hover style will take precedence and override the standard style.
Traditionally the CSS mouseover behavior of the :hover pseudo-class is for hyper-link anchors ( tags), to improve the user experience by letting users know that the hyper-link is interactive. However, it can be used on nearly anything. Standard usages include: customizing behavior of text hyper-links, changing the source of an image link, or changing the style of a form button.
Please be aware that there are three other pseudo-classes designed specifically for hyper-link anchors ( tags), and they must be listed in a specific order within your CSS for them to work property. In descending order they are :link for unvisited links, :visited for visited links, :hover, and :active for selected links.
Further Reading
This article assumes that you have an introductory knowledge of CSS, including common CSS terms and how to apply styles to your web pages. For more information on these subjects please see the article Getting Started with Basic CSS Code.