Styling the Radio Buttons

Published 06 Dec by SuperNOVA

Styling the Radio ButtonsRadio Buttons are an important part of the HTML forms. They are the most appropriate element when the user needs to input a choice. So, we will discuss how we can beautify these little things with some CSS magic.
Lets get down to business, the trick is to hide the default radio buttons and displaying an image instead. Lets consider this piece of code: Super basic stuff, this just renders two radio buttons with different values which your php code can process. Although I have used a label which serves a small advantage ahead, you can even achieve the desired effect without labels if you use the right selectors and jQuery. This is what the above renders:
In Love?

Very ugly, I know! Lets remedy that shall we?
Add the following CSS which will do the magic. Before anything, lets see what the above code does:
In Love?

Now let me explain what we did: We hid the default radio buttons, now we added a background-image to the span.rad_img. This image is of the unselected radio button.
In the next rule we change the background-position or in layman terms we changed the image of the selected radio button. We did this by using this selector: input[type=”radio”]:checked + span.rad_img. this selects the span with a class “rad_img” which comes directly after the checked radio button. Since, I used everything inside the label I didn’t have to add any javascript handlers.

Now, if you have a different situation where you can’t use a label you can use jquery’s trigger() function or even change the selected attribute for the radio buttons. By using the same logic you can also style the checkboxes by using appropriate images.

With time I have found this technique very helpful, but if you have a better technique in any sense of the word “better” please do share!