Styling radio inputs

No styling

This is a typical radio input:




<input type="radio" name="myradio" id="myidA" checked />
<label for="myidA">Input A</label>

<input type="radio" name="myradio" id="myidB"/>
<label for="myidB">Input B</label>

<input type="radio" name="myradio" id="myidC"/>
<label for="myidC">Input C</label>

<input type="radio" name="myradio" id="myidD"/>
<label for="myidD">Input D</label>

These are type="radio" inputs. The <label> tag is a complementary to the radio input. When you click on the text, it selects the input. Easy, right?

No CSS support

Say you want to add some custom styling to these radio inputs. Unfortunately, CSS doesn't really support that.


input[type='radio'] {
  background: red;
  border: 2px solid cyan;
  //and so on...
}

The code above has no effect (or not the desired effect) on the appearance of the radio button.

You can use height and width, but that's pretty much all there is to it.


input[type='radio'] {
  height: 20px;
  width: 20px;
}

Using labels

So what now? CSS doesn't work styling the buttons! But, we CAN use CSS to style the <label> tag!


label {
  padding: 15px;
  display: inline-block;
  background: dimgrey;
  color: whitesmoke;
  transition: all 0.25s;
  cursor: pointer;
}

label:hover {
  background: whitesmoke;
  color: dimgrey;
}

I made the label look like a button, but you can use whatever you want.

CSS selectors

Now we want the labels to change when the radio button is checked. For that we will use the + selector CSS gives us. It targets the next element on the same node level. W3Schools entry

CSS also has the :checked selector. It targets (you guessed it) selected elements!

If we now combine these two features, we can target the next element that comes after a selected radio button.


input[type='radio']:checked + label {
  background: crimson;
  color: whitesmoke;
}

Nice! That already looks a lot better. Last thing we want to do, is getting rid of the button next to the label tag.


input[type='radio'] {
  display: none;
}

TL;DR (too long, didn't read)

Using labels to style radio buttons is definitely the way to go. It's relatively easy and the concept can be applied to checkbox inputs. Here is the code you need to use.

HTML

<input type="radio" name="myname" id="myidA"/>
<label for="myidA">Input A</label>

<input type="radio" name="myname" id="myidB"/>
<label for="myidB">Input B</label>

CSS

label {
  display: inline-block;
  //your CSS code for the default input
}

input[type='radio'] {
  display: none;
}

input[type='radio']:checked {
  //your CSS code for when the input is checked
}

Be sure to leave a comment if you liked this post or if this helped you! Thank you :D

- ninivert