uvd_8a
Last Updated: February 25, 2016
·
6.791K
· nathansmonk
1341762883

Sprite-less CSS Rollovers with CSS3 transitions

If sprites are not an option then CSS rollovers can have an issue: when the browser tries to load the hover state image, you'll see a flash of the background before the image has loaded. This is because the browser is loading the image as it is requested. What we need to do is preload the image.

To get super simple CSS rollovers that preload the second image, you just need the following HTML markup:

<a href="http://www.wearesmile.com" alt="SMILE" class="rollover"><span></span></a>

Then for the CSS, we add the default state (which is the <span>):

a.rollover span {
background-image:url('/assets/happy-kitten.jpg');
width: 100%;
height: 100%;
display: block;
}

The width and height should be set to 100% which will expand it to that of the parent element so should you need to make an edit, you'll only need to define one set of dimensions. The display declaration will also make more sense once we've styled the parent element with the actual dimensions.

After that, we need to add the hover state using this:

a.rollover {
background-image:url('/assets/happy-kitten.jpg');
height: 100px;
width: 100px;
display: block;
}

You'll notice that we also added in the dimensions of the rollover and the display declaration to make sure that it is treated as a block element that will adhere to the dimensions that we set.

Then the magic is supplied by one last chunk of CSS:

a.rollover span:hover {
opacity: 0;
transition: opacity .25s ease-in-out;
-moz-transition: opacity .25s ease-in-out;
-webkit-transition: opacity .25s ease-in-out;
}

This means that when the user hovers over the span, it becomes transparent (via a CSS3 transition to create the fade effect) leaving the parent element background image visible. If you need to modify the rollover, everything apart from the link can be controlled from within your CSS.

And because both the elements background images are loaded at the page load, there are no flashes of the background!

Say Thanks
Respond