Yogesh Chauhan's Blog

How to convert an HTML radio buttons into a toggle switch using CSS?

in CSS & HTML on March 28, 2021

HTML

Let’s start with a simple HTML. Nothing fancy we need here.

CSS

To give those input radio buttons a switch appearance, we need to have those elements next to each other. For that we can use multiple ways for e.g. making the container a flex or a grid or just set the margin 0.

We’ll go with a flex option.

Also, we’ll remove the original radio button and convert the labels into our switch. Let’s remove the radio buttons first. We can just set the height and width to 0.

Even after that, we’ll see two small dot of radio buttons. We’ll remove those by setting the position property of those radio buttons as an absolute and clipping it afterwards.

Just like this:

Let’s make the switch now by applying some basic styles to the labels.

We still need style when the input radio button is selected. Let’s add that now.

Looks nice. Let’s carve out the corners of those labels to make it look nice. We can target those labels by adding ID or class or simply just by first-of-type and last-of-type.

Just like this:


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Learn to create profile card using HTML and CSSCSSCheck whether a variable exists and not empty in PHPPHPHTML canvas methodsHTMLHow to add Google Static Map using ACF map field?WordPressHow to Find the Highest (or Lowest) Number in an Array in JavaScript?JavaScriptGeneral concepts in DrupalDrupalHow To Create a Fullscreen Background Video using CSS and JavaScript?CSSfirst-of-type and last-of-type selectors in CSSCSSShould we ever delete data from a database?MiscellaneousHow to create Glowing Texts using CSS?CSSHow to add navigation menu in Angular 9 app?AngularHow to show and hide an element on click in React?React