The following example shows a slightly more thorough version of the example we've seen throughout the article, with some additional styling, and with better semantics established through use of specialized elements. The HTML looks like this:
Please select your preferred contact method:
name="contact" value="email" checked>
name="contact" value="phone">
Phone
name="contact" value="mail">
Submit
There's not much new to note here except for the addition of
and elements, which help to group the functionality nicely and in a semantic way.The CSS involved is a bit more significant:
html {
font-family: sans-serif;
}
div:first-of-type {
display: flex;
align-items: flex-start;
margin-bottom: 5px;
}
label {
margin-right: 15px;
line-height: 32px;
}
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border-radius: 50%;
width: 16px;
height: 16px;
border: 2px solid #999;
transition: 0.2s all linear;
outline: none;
margin-right: 5px;
position: relative;
top: 4px;
}
input:checked {
border: 6px solid black;
}
button,
legend {
color: white;
background-color: black;
padding: 5px 10px;
border-radius: 0;
border: 0;
font-size: 14px;
}
button:hover,
button:focus {
color: #999;
}
button:active {
background-color: white;
color: black;
outline: 1px solid black;
}
Most notable here is the use of the -moz-appearance property (with prefixes needed to support some browsers). By default, radio buttons (and checkboxes) are styled with the operating system's native styles for those controls. By specifying appearance: none, you can remove the native styling altogether, and create your own styles for them. Here we've used a border along with border-radius and a transition to create a nice animating radio selection. Notice also how the :checked pseudo-class is used to specify the styles for the radio button's appearance when selected.
Compatibility note: If you wish to use the appearance property, you should test it very carefully. Although it is supported in most modern browsers, its implementation varies widely. In older browsers, even the keyword none does not have the same effect across different browsers, and some do not support it at all. The differences are smaller in the newest browsers.
Notice that when clicking on a radio button, there's a nice, smooth fade out/in effect as the two buttons change state. In addition, the style and coloring of the legend and submit button are customized to have strong contrast. This might not be a look you'd want in a real web application, but it definitely shows off the possibilities.