Use CSS to style a checkbox input as a flip switch and maintain the appearance of its label

Is there a way to style an input of type checkbox using only CSS, while still keeping the existing label associated with it?

<p id="lorem-ipsum">
    <label for="dolor-sit-amet">Dolor sit amet</label>
    <input type="checkbox" id="dolor-sit-amet" name="dolor" />
</p>

I am looking to give the checkbox a "flip switch" appearance and behavior.

Preserving the current label

While there are many resources available that show how to completely customize the look of a checkbox, I have not come across any that allow the label (as used in the example above) to remain unchanged.

Therefore, solutions provided in a related StackOverflow thread on stylizing checkboxes may not be applicable in this case.

In essence: my goal is to keep the existing label as is, and style the checkbox as a flip switch with "on" and "off" options inside it.

How can I achieve this without altering or customizing the current label, but instead focusing on styling the input element?

Answer №1

Want to switch up the order of label and input? Here's an idea for you: customize the colors and add animations based on your preferences.

label{
position:relative;
display:block;
width:200px;
}
label:before{
  content:'off';
  width:50px;
  height:20px;
  background:#eee;
  border-radius:50px;
  position:absolute;
  right:0;
  
}
label:after{
  content:'';
  width:18px;
  height:18px;
  background:#333;
  border-radius:50px;
  position:absolute;
  right:1px;
  top:1px;
  
}
input:checked + label:before{
  content:'on';
  text-indent: 25px;
  
  
}
input:checked + label:after{
  right:29px;
  top:1px;
  
}
<p id="lorem-ipsum">
    <input type="checkbox" id="dolor-sit-amet" name="dolor" />
    <label for="dolor-sit-amet">Dolor sit amet</label>
    
</p>

Answer №2

Using the :before and :after selectors allows for the creation of additional content. By introducing another element (such as a span) that can be styled to mimic a “slider” within a switch.

The parent element – which could even be the label itself! – can also utilize the :before and :after selectors to design the container in which the slider moves.

input[type=checkbox].switch {
    display: none;
}

label.switch.socket {
    position: relative;
    width: auto;
    text-indent: 6.0ex;
}
span.switch.slider {
    display: inline-block;
}
label.switch.socket span.switch.slider:before {
    content: "off";
    text-indent: 2.3ex;
    width: 5.5ex;
    height: 2.2ex;
    color: White;
    background: DimGray;
    border-radius: 5.5ex;
    position: absolute;
    left: 0;
}
label.switch span.switch.slider:after {
    content: "";
    width: 2.0ex;
    height: 2.0ex;
    background: Gainsboro;
    border-radius: 5.5ex;
    position: absolute;
    left: 0.1ex;
    top: 0.1ex;
    transition: 0.2s;
}
label.switch.socket input[type=checkbox]:checked + span.slider:before {
    content: "on";
    text-indent: 0.5ex;
    color: Black;
    background: DarkGray;
}
label.switch.socket input[type=checkbox]:checked + span.slider:after {
    left: 3.4ex;
}
<p>
    <label class="switch socket">
        <input type="checkbox" class="switch" name="lorem" />
        <span class="switch slider" />
        Lorem ipsum
    </label>

    <label class="switch socket">
        <input type="checkbox" class="switch" name="dolor" checked />
        <span class="switch slider round" />
        Dolor sit amet
    </label>
</p>

(Gratitude to @gosi123 and @aje for their insightful suggestions that helped inspire this response.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript function that fetches data from local storage and displays it in an HTML table

I've been exploring how to incorporate a bootstrap datatable into my project. Rather than using pre-set data, I want to allow users to input their own data through a form and store it in localStorage. Understanding that I need to stringify and parse ...

What is the best way to keep track of a checkbox's value after unchecking it and then returning to the same slide?

Issue: By default, the checkbox is always set to true in the backend code. Even if I uncheck it using JavaScript, the value remains as true when switching between slides. Desired Outcome: If I uncheck the checkbox, the updated value should be saved so tha ...

Unusual css glitch observed when hovering over a span/link

Currently, I'm struggling with a CSS code issue. My goal is to have the div #hidden show when someone hovers over the link in #trigger. <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> ...

My intention is to personalize the react-select component to suit my needs

My task involves changing the size of the arrow to be smaller and positioning it under the circle. Despite setting the width and height in the CSS, the desired effect is not achieved. To align with the UI requirements, I need to adjust the swiper-button- ...

The Bootstrap popover fails to display

I am trying to display a popover on my website, but I am unable to see it. CODE echo ' <a data-toggle="popover" data-trigger="hover" data-html="true" data-placement="top" ...

I'm confused as to why the CSS Bottom property is causing the top edge of the div to align with the bottom of the document rather than the bottom edge

My challenge is to align an image slideshow on top of my footer, with the bottom edge of the slider touching the top edge of the footer. Despite using position: fixed and bottom: 0 properties, it appears that the positioning is off - aligning the top edge ...

Creating a Distinctive HTML Structure with Div Percentage (HTML 4)

I am new to web design and have a unique approach; I believe in the importance of flexibility. It puzzles me why pixels (px) are commonly used instead of percentages, maybe my perspective is misunderstood. I've been on the hunt for a basic HTML layo ...

Customizing the appearance of an Ant-Design 'Select' component: A step-by-step guide

If I wanted to change the default white background color of the Select component to green, what would be the correct approach? My attempt... <Select style={{ backgroundColor: 'green' }}> // Options... </Select> ...did not work ...

Choosing an option will display a specific div while hiding another using JQuery

My question involves a Select Option <select class="input_select" name="customer_type" id="central_company"> <option value="standard">Standard</option> <option value="central">Central Station</option> </select> ...

Unable to modify jwplayer css styles to customize the chromecast icon

Is there a way to customize the chromecast icon within the JWPlayer skin to have a specific color? I've identified that the styles I need to change are --connected-color and disconnected-color when inspecting the element. Despite my attempts through ...

Tips for resolving vertical alignment styling for images of varying sizes within Vue.js transition-group?

I have created an image slider example, but I'm facing a styling issue when using images of different dimensions. The element leaving the array is positioned absolutely for smooth transitions, but this causes the image to move up. I am trying to vert ...

What is the best way to change the size of a QR code

My current HTML code: <input id="text" type="text"/> <div id="qrcode"></div> Previous version of JAVASCRIPT code: var qrcode = new QRCode("qrcode"); $("#text").on("keyup", function () { qrcode.makeCode($(this).val()); }).keyup().focus ...

Looking to Identify a Click Within a Complicated Component and Retrieve the Component's ID

Currently, I am working with React for development and have a need to capture clicks at the topmost parent level for performance reasons. const clickHandler = (e) => { console.log("clickHandler", e.target) --> I want to identify the child ...

What is the best sequence for loading angularjs, bootstrap, sp js libraries, and jquery?

I have a unique single application that requires the use of bootstrap, ui bootstrap, angularjs, and jquery. The functionality of the button below is working correctly, but I am experiencing issues with the styling. You can check out a sample of alerts here ...

The MUI component with hideBackDrop={true} is preventing me from clicking outside of the Drawer component to close it

I implemented a Drawer component which opens when an icon on the Map is clicked. The drawer menu appears along with a backshadow that drops over the map. Interestingly, clicking on the map while the backshadow is displayed closes the drawer without any i ...

Updating navbar in Bootstrap 4.5 to accommodate limited space

Snippet of Code (With Bootstrap 4.5): $(".self-first-ul").append('<li class="nav-item">A lengthy sentence that is too long for small screens.</li>'); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min. ...

Fill various dropdowns with a list or array of values discreetly without displaying the populated values on the visible interface

I have an array with values 1,2,3,4. Using an add function, I am able to create multiple dropdowns. By default, the first dropdown always has a value of one when initially set up. When we press add and populate the second dropdown with values 2,3,4, tho ...

Trouble with the Javascript function for Clearing Fields?

I wrote a function to clear text fields, but it doesn't work when custom values are entered. function clear(){ document.getElementById('bmw1').value=""; document.getElementById('bmw2').value=""; document.getElementByI ...

How to customize tag option borders to blue with a blue background on hover in Chrome [Unable to find solution elsewhere]

Struggling to eliminate the blue border and blue background on hover from a select tag option. Despite searching for solutions, none seem to work as desired. Some codes helped change the background, but not what I intended to achieve. Any guidance would ...

Ways to navigate to a different page using HTML response from an AJAX request

After receiving an HTML document as a response from an AJAX call, I need to create a redirection page using this HTML response. Can anyone provide guidance on how to achieve this? ...