expLog

 — an experimental weblog

Styling attractive CSS/Radio Buttons

Styling Radio Buttons and Check Boxes across Browsers and Operating Systems is a relatively hard task, simply because of the way the elements are rendered by various browsers; integrating the design with your website’s is a bit harder. This is a fairly simple trick I haven’t seen mentioned in any of the CSS sites I’ve read recently.

A small demonstration to whet your appetite first:

The basic idea is to hide the form element (checkbox/radio button) and style the label instead using CSS. Thanks to the :checked selector, it’s possible to distinguish between the two label states by assigning styles to label and input:checked + label assuming that the label follows the checkbox/radio button in your html code. Using a for attribute in the code makes the complete label click-able, modifying the state of the associated element.

A simple trick to make beautiful form elements without having to use javascript: and the styling will in no way affect any server side or script based code because the state of the checkbox/radio button is maintained.

The code:

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
47
48
49
50
51
52
53
54
55
56
57
58
59
<!-- Demo 1 -->
<style type = 'text/css'>
input.demo-1 { display: none }
label.demo-1 {
background-color: #ddd;
text-shadow: 0 1px 0 #fff;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.44, rgb(184,184,184)),
color-stop(0.72, rgb(212,212,212))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(184,184,184) 44%,
rgb(212,212,212) 72%
);
color: #555;
border-radius: 5px;
padding: 10px;
display: inline-block;
cursor: pointer;
border: solid #000 1px;
}
input.demo-1:checked + label.demo-1 {
color: #002;
background-color: #00f;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.44, rgb(134,235,129)),
color-stop(0.72, rgb(165,240,153))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(134,235,129) 44%,
rgb(165,240,153) 72%
);
border: solid 1px #99f;
}
input.demo-1:checked + label.radio {
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0.44, rgb(54,146,227)),
color-stop(0.72, rgb(100,192,242))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(54,146,227) 44%,
rgb(100,192,242) 72%
);

border: solid 1px #999;
}
</style>

Comments

/notes/formstyling.html last updated on 20/07/2011. © 2011 Kunal Bhalla