Section IV.4. CSS-Only Image Swaps


IV.4. CSS-Only Image Swaps

You can also fashion a variety of "rollover" effects using Cascading Style Sheet rules without any scripting. The images are not put into the markup as <img> tags, but rather as background images to links styled as block-level elements. In lieu of scripted mouse events, you code the style rules to use the :hover pseudo-class (and, optionally, :active for the equivalent of a mousedown event) to change the background image URL.

You can also take advantage of CSSalong with carefully crafted imagesto eliminate the need for precaching images. A single image file contains both the normal and highlighted versions of the button, side-by-side. By shifting the position of the background image during a hover action, the browser appears to be swapping the image.

The following HTML markup serves as the basis for one solution to the CSS approach:

 <a href="index.html"  ></a> <a href="catalog.html"  ></a> <a href="about.html"  ></a> 

In this case, there is no content for the a elements, which could be a problem for older browsers and search engine crawlers. But your design can also be such that button labels are comprised of HTML text, if you can find font style properties that work across a wide range of browsers.

All the rest of the work occurs in the CSS rules, as follows:

 <style type="text/css"> a.cssswappable {    display: block;    text-decoration: none;    height: 70px;    float: left;    margin-right: 4px; } #csshome {    width: 147px;    background-image: url(img/home.png);    background-position: left; } #csshome:hover {    background-position: right; } #csscatalog {    width: 189px;    background-image: url(img/catalog.png);    background-position: left; } #csscatalog:hover {    background-position: right; } #cssabout {    width: 209px;    background-image: url(img/about.png);    background-position: left; } #cssabout:hover {    background-position: right; } </style> 

When designing pages that rely on the :hover pseudo-class, keep one important compatibility issue in mind: Internet Explorer prior to Version 7 supports the mouse-related pseudo-classes only for a elements. Other modern browsers (including IE 7 in standards-compatible mode only) support them for all types of rendered elements.

You can mix CSS and scripted rollover techniques to match your markup and accessibility requirements. For example, if you prefer to use an anchor (a) element around an img element, you can use a combination of mouseover/mouseout events for the a element that trigger scripts that alter CSS background image position for an img element that contains a transparent image.




Dynamic HTML. The Definitive Reference
Dynamic HTML: The Definitive Reference
ISBN: 0596527403
EAN: 2147483647
Year: 2004
Pages: 120
Authors: Danny Goodman

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net