Rollover Effects for Images with CSS
When you move your mouse cursor over an image on a Web page, you may see an animated rollover effect created using JavaScript or CSS. Rollovers occur when a Web page replaces one image with another in response to the movement of a user’s mouse. Sites do not need rollovers, but these effects can add visual interest to Web pages. If you don't know JavaScript and you'd like to add image rollovers to your website, you can do that using CSS.
-
CSS Rollovers
-
CSS rollover effects require more work to set up than JavaScript rollover effects, but there are benefits to using CSS to create image rollovers. When you use CSS, you reduce the time it takes for your Web server to transfer the images used in the effect to a user’s Web browser. You also make your rollover effects visible to all site visitors, instead of just the ones who enable JavaScript in their browsers.
CSS Properties
-
Site owners use CSS to style objects on their webpages. CSS attributes such as background-color, border and width define the way images look on a Web page. CSS classes define these attributes. The following CSS class contains two attributes, named border-width and border-style:
.cssClass {
border-width: 2px; border-style:solid;
}If an image references this class, the image will display a solid border that's two pixels wide. CSS classes can also add a background image to a Web page element.
-
Image Sprites
-
Developers add CSS rollover effects to websites by placing sprites on their pages. A sprite is a large image made up of smaller images. Create a sprite in an image editor by placing two adjacent images inside a larger blank image. The image on the left will be the image that site visitors see when your Web page loads. The image on the right will be the one you want to display when a mouse moves over the sprite. Both images must be the same size.
Anchor Tags Needed
-
HTML anchor tags, also called links, make CSS image rollovers possible. Anchor tags can use CSS pseudo classes that define the way a link looks when a mouse moves over the link. The following example shows a pseudo class named "hover" attached to a regular CSS class named myClass:
a.myClass:hover { background-position: -300px 0; }
Any anchor that references this class will shift its background image 300 pixels to the right when a mouse rollover occurs, creating the rollover effect. The anchor tag must also reference the main CSS class that defines the height and width of each image in your sprite.
-
References
Resources
- Photo Credit Thinkstock Images/Comstock/Getty Images