HTML/CSS - Replacing Browser radiobutton with custom images

2014-02-04

For the project I’m working on now, I need to display a custom radio button image. The example from the design studio used custom javascript to define a PrettyButton object. This then responded to clicks and changed classes.

If you don’t care about IE8 anymore, or can accept the default radiobutton icons for IE8 and the custom ones for above that, and would rather use nothing more than HTML and CSS to control the radiobuttons, then the link below will be very useful.

http://www.thecssninja.com/css/custom-inputs-using-css

Using the technique described there, I’ve create a minimalist html document with inline style to demonstrate the technique. This example doesn’t show the hover effect, but the other aspects are visible.
`

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html>
<head>
    <title>Radio Image</title>
    <style>
        .form-group {
            height: 25px;
        }

        .form-group > input {
            opacity: 0;
            position: absolute;
        }

        .form-group > input + label {
            background-image: url('img/radio-large.png');
            background-repeat: no-repeat;
            background-position: 0 0;
            padding: 0 0 0 33px;
            display:block;
            height: 21px;
            vertical-align: middle;
            line-height:21px;
        }
        .form-group > input[type=radio]:checked + label {
            background-position: 0 -21px;
        }
    </style>
</head>
<body>
    <form name="quiz-1">
        <div>
            <input id="radio1" type="radio" name="radio-choice" value="choice1"/>
            <label for="radio1"> I like choice 1</label>
        </div>
        <div>
            <input id="radio2" type="radio" name="radio-choice" value="choice2"/>
            <label for="radio2"> I like choice 2</label>
        </div>
        <div>
            <input id="radio3" type="radio" name="radio-choice" value="choice3"/>
            <label for="radio3"> I like choice 3</label>
        </div>
    </form>
</body>
</html>

And the image used for the buttons is:
radio-large

One caveat. I haven’t verified this works in IE9, and I haven’t shown the method described in the post to degrade nicely on IE8.


Comments: