How do you point to various images for various button states? Onmouseover, etc.
+4
A:
HTML
<button>Hello</button>
CSS
button {
background: url(your-image.png) no-repeat;
}
button:hover {
background: url(your-image-hovered.png) no-repeat;
}
button:focus {
background: url(your-image-focused.png) no-repeat;
}
Note: The :focus
and :hover
pseudo classes are not supported on all IE versions (on buttons at least). You can use JavaScript to emulate. Check out the events blur()
and focus()
(to emulate :focus
) and onmouseover()
and onmouseout()
(to emulate :hover
).
Alternatively, if you need to support a very ancient browser (quite unlikely), you can use JavaScript, but is not recommended in this day and age when CSS provides this functionality.
alex
2010-05-10 01:39:43
Argh. I was typing out this same example with the below preamble: -- There are a few different approaches for changing the button states. You can use events like onmouseover and onmouseout to change the button's display.I suggest using the CSS approach -- specifically the `:hover` pseudo class. This approach uses less code and works even if Javascript is disabled in the browser *but* is not supported in IE6. --When you beat me to the punch.
Christopher Altman
2010-05-10 01:41:31
I would add the background position to the above CSS: background:url(your-image.png) top center no-repeat;
Christopher Altman
2010-05-10 01:43:08
@Christopher Sorry! I might actually go do some work now :)
alex
2010-05-10 01:43:42
@Christopher Regarding the background position, it really depends on where he wants the image. I've left this decision at his discretion.
alex
2010-05-10 01:44:38
To avoid repeating the `no-repeat` (heh), split up `background` into `background-image` and `background-repeat` and let CSS take care of the 'duplication'. If you add things like background position, you won't have to modify the CSS in three places, only one.
strager
2010-05-10 11:12:00
@strager Correct, but I thought I wouldn't go into CSS optimizations in this little sample.
alex
2010-05-12 00:14:15