Many times on a web site you will want to have a button have three distinct visual states: normal, active, and hover. This is easily accomplished using HTML and CSS. This post will provide the details necessary to accomplish a three state button.
First we need to create an image to represent the three states of our button. The following image represent all three states combined into one image called a sprite. It is much faster to download one image than three images.
Top Image: Normal state
Middle Image: Hover state
Bottom Image: Active state
The image is 70 pixels wide by 150 pixels tall (each is 50 pixels).
The markup to create the three state buttons is shown below:
Here we use an un-ordered list as a container for the button options. The active element for each button is an anchor tag. In the example above, the anchors are not wired up (href is not set). Two CSS classes are used in the above markup. One sets the un-ordered list to be transformed into a three state button list (‘buttons’) and the other marks one of the buttons as ‘active’
The following CSS is used to style the above markup.
margin: 0 2px;
ul.buttons li a
background: transparent url(images/menu-sprite.png) no-repeat scroll 0 0;
padding: 25px 0 0 0;
ul.buttons li a:hover
background-position: 0 -50px;
ul.buttons li.active a, #header ul.buttons li.active a:hover
background-position: 0 -100px;
First we style the ul element to not use the standard bullet point image. Then we float each li element left. This takes the normal vertical stack of li elements and allows them to be rendered horizontally. The 2px left / right margin allows the buttons elements to be spaced a bit when displayed.
The last three CSS rules style the anchor tag. The first rule sets the image that we created as the background. Note that the width of the anchor is set to 70px and the total height (height + padding) is 50px which matches the size of one of our image buttons. The padding is necessary in this example because I wanted to push the text down towards the bottom of the image. This combination of padding & height will have problems in older browsers. In this case, additional markup may be necessary to position the text.
The key to selecting the correct state image is the ‘background-position’ style. For normal anchors this is set to 0px (default). For hover over anchors the value is –50px. And for anchors with the ‘active’ class the value is –100px. This indexes into our sprite and causes the correct image to be displayed.
Creating a three state button is simple and only requires the following:
- a sprite containing the three visual states (normal, hover, active)
- HTML containing an un-ordered list
- CSS to style the un-ordered list and using the ‘background-position’ to set the states for the anchor tags.