Skip to main content

Styling Input of type radio

Styling radio buttons can be a bit more challenging than other form elements due to browser inconsistencies and limitations. However, with modern CSS techniques, you can create custom radio buttons that enhance user experience.

Basic Styling​

Hiding Native Radio Buttons​

The first step in custom styling is often to hide the native radio button, but keeping it accessible for screen readers.

input[type="radio"] {
opacity: 0;
position: absolute;
}

Custom Styling with Pseudo-elements​

You can use pseudo-elements to create custom radio buttons. The ::before and ::after pseudo-elements are commonly used for this purpose.

input[type="radio"] + label {
position: relative;
padding-left: 35px; /* Space for custom radio */
cursor: pointer;
}

input[type="radio"] + label::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 25px;
height: 25px;
border: 2px solid #ccc;
border-radius: 50%;
}

input[type="radio"]:checked + label::after {
content: "";
position: absolute;
left: 9px;
top: 9px;
width: 11px;
height: 11px;
background-color: #007bff;
border-radius: 50%;
}

Interactive States​

You can also style the radio button for different states like hover, focus, and disabled.

input[type="radio"]:hover + label::before {
border-color: #007bff;
}

input[type="radio"]:focus + label::before {
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

input[type="radio"]:disabled + label {
opacity: 0.6;
cursor: not-allowed;
}

Accessibility​

  1. Labels: Always use <label> elements with a for attribute that matches the id of the input.
  2. ARIA Attributes: Use ARIA attributes like aria-checked for enhanced screen reader support.

Example HTML​

Here's how your HTML might look:

<input type="radio" id="option1" name="options">
<label for="option1">Option 1</label>

<input type="radio" id="option2" name="options">
<label for="option2">Option 2</label>

Complete Example​

Combining all the above, here's a complete example:

index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="./main.css" >
</head>
<body>
<header></header>
<form>
<span>
<label for="fName">First Name</label>
<input id="fName" name="fName" pattern="[A-Za-z]{3,}" type="text" >
</span>
<div>
<p> Select your gender</p>
<span>
<input id="male" type="radio" name="gender" >
<label for="male">Male</label>
</span>
<span>
<input id="female" type="radio" name="gender" >
<label for="female">FeMale</label>
</span>

</div>
</form>
</body>
</html>