DEV Community

Cover image for Create Custom Radio Buttons with CSS Animation
Labby for LabEx

Posted on

Create Custom Radio Buttons with CSS Animation

Introduction

This article covers the following tech skills:

Skills Graph

In this lab, we will explore CSS programming concepts by creating a custom radio button with animation on state change. The lab will guide you through the process of using flexbox to create a layout for the radio buttons, resetting the styles on the <input> element, and using the ::before element to create the inner circle of the radio button. By the end of the lab, you will have a better understanding of CSS styling and animation techniques.

Custom Radio Button

index.html and style.css have already been provided in the VM.

To create a styled radio button with animation on state change, follow these steps:

  1. Create a .radio-container using flexbox to create the appropriate layout for the radio buttons.
  2. Reset the styles on the <input> and use it to create the outline and background of the radio button.
  3. Use the ::before element to create the inner circle of the radio button.
  4. Create an animation effect on state change by using transform: scale(1) and a CSS transition.

Here is an example HTML snippet:

<div class="radio-container">
  <input class="radio-input" id="apples" type="radio" name="fruit" />
  <label class="radio" for="apples">Apples</label>
  <input class="radio-input" id="oranges" type="radio" name="fruit" />
  <label class="radio" for="oranges">Oranges</label>
</div>
Enter fullscreen mode Exit fullscreen mode

And here is the corresponding CSS:

.radio-container {
  display: flex;
  align-items: center;
}

.radio-container * {
  box-sizing: border-box;
}

.radio-input {
  appearance: none;
  width: 16px;
  height: 16px;
  margin: 0;
  border: 1px solid #cccfdb;
  border-radius: 50%;
  display: grid;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.radio-input::before {
  content: "";
  width: 6px;
  height: 6px;
  border-radius: 50%;
  transform: scale(0);
  transition: 0.3s transform ease-in-out;
  box-shadow: inset 6px 6px #ffffff;
}

.radio-input:checked {
  background: #0077ff;
  border-color: #0077ff;
}

.radio-input:checked::before {
  transform: scale(1);
}

.radio {
  cursor: pointer;
  padding: 6px 8px;
  margin-right: 6px;
}
Enter fullscreen mode Exit fullscreen mode

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Custom Radio Button lab. You can practice more labs in LabEx to improve your skills.

MindMap


πŸš€ Practice Now: Custom Radio Button


Want to Learn More?

Top comments (0)