When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript? Are there any performance or code maintainability issues I should be aware of with either approach?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
CSS is fine for rollovers. They’re implemented basically using the
:hoverpseudo-selector. Here’s a really simple implementation:There are a few things you need to be aware of though:
:hoveron<a>tagsThe
<a>-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called CSS Sprites that can prevent this problem, you can find an example of the technique in use to make no-preload rollovers.It’s pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using
background-positionso only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background – no extra files need to be loaded at all. Here’s a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states – one on top of the other (so the image is 40px high)):Note that using this ‘sprites’ technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don’t support
background-position)