Custom_checkboxes and radio buttons are a stylish way to customize the look of your HTML forms, but they can also be a bit tricky to create. In this tutorial, we'll go over how to create custom checkboxes and radio buttons using only CSS.
First, let's start with the HTML. We'll create a simple form with a group of checkboxes and a group of radio buttons.
<form>
<div>
<input type="checkbox" id="checkbox1" name="checkbox1" value="option1">
<label for="checkbox1">Option 1</label>
</div>
<div>
<input type="checkbox" id="checkbox2" name="checkbox2" value="option2">
<label for="checkbox2">Option 2</label>
</div>
<div>
<input type="radio" id="radio1" name="radio" value="option1">
<label for="radio1">Option 1</label>
</div>
<div>
<input type="radio" id="radio2" name="radio" value="option2">
<label for="radio2">Option 2</label>
</div>
</form>
Next, let's style the checkboxes and radio buttons to remove the default styles. We'll do this by targeting the input
element and setting the appearance
property to none
.
input[type="checkbox"],
input[type="radio"] {
appearance: none;
}
Now that we've removed the default styles, we can add our own custom styles. We'll start by creating a custom checkmark icon using theĀ ::before
pseudo-element.
input[type="checkbox"]::before,
input[type="radio"]::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
border: 1px solid #ccc;
border-radius: 50%;
margin-right: 8px;
}
Next, we'll style the checked state of the checkboxes and radio buttons. For the checkboxes, we'll use the :checked
pseudo-class. For the radio buttons, we'll use the :checked
pseudo-class and the :not(:checked)
pseudo-class to style both the checked and unchecked states.
input[type="checkbox"]:checked::before {
background-color: #333;
border-color: #333;
}
input[type="radio"]:checked::before {
background-color: #333;
border-color: #333;
}
input[type="radio"]:not(:checked):before {
background-color: #fff;
border-color: #ccc;
}
Finally, let's add some hover and focus styles. We'll use theĀ :hover
andĀ :focus
pseudo-classes to change the border color of the checkboxes and radio buttons when they are hovered or focused.
input[type="checkbox"]:hover::before,
input[type="checkbox"]:focus::before,
input[type="radio"]:hover::before,
input[type="radio"]:focus::before {
border-color: #333;
}
Final result!
And that's it! With just a few lines of CSS, we've created custom checkboxes and radio buttons that are easy to style and fully functional. You can use these techniques to create a wide range of custom form elements that match the design of your website.