Ways to modify the look of a checkbox when it is checked, without using extra elements

Is there a way to change the color of a checkbox, label, or any other element using only CSS based on the :checked selector? The HTML code is provided below and cannot be changed.

<div class="chk">
    <label>
        CheckMe
        <input type="checkbox" id="myCheckBox">
    </label>
</div>

I have attempted to use input[type="checkbox"] + label:before in my CSS, but since the label actually contains the checkbox rather than coming after it, this approach doesn't work.

I also tried creating pseudo-elements after the label and checkbox, but I couldn't get that method to work either.

I am essentially seeking a similar functionality as shown in this example: http://jsfiddle.net/zAFND but utilizing only CSS and without being able to modify the HTML structure.

Answer №1

input[type="checkbox"]:checked {
border-radius: 2px;
appearance:none;
-webkit-appearance:none;
-moz-appearance:none;
width: 17px;
height: 17px;
cursor:pointer;
position: relative;
top: 5px;
background-color:#409fd6;
background:#409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;

}
<div class="chk">
    <label>
        CheckMe
        <input type="checkbox" id="myCheckBox">
    </label>
</div>

Answer №2

If you want to achieve this effect, Jquery is the way to go.

$("input").click(function() { 
    $(this).parent().toggleClass('checked');
})

By doing this, the class checked will be toggled for the parent label whenever the input changes.

You can now apply your own custom styling to it.

$("input").click(function() { 
    $(this).parent().toggleClass('checked');
})
  label { 
    padding: 10px 20px;
    border-radius: 3px;
}

.checked { 
    background-color: red;
    color: white;
}
<div class="chk">
      <label>
        CheckMe
        <input type="checkbox" id="myCheckBox" />
      </label>
      <script src="node_modules/jquery/dist/jquery.js"></script>
      <script src="index.js"></script>
    </div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №3

Solution: Here is a code snippet that you can use...

label{
  position: relative;
  padding: 15px;
  color: #000;
  z-index: 1;
  margin-top: 20px;
  display: block;
}
input{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  appearance:none;
  -webkit-appearance:none;
  -moz-appearance:none;
  outline: none;
}
input:after{
  content: "";
  top: 0;
  left: 0;
  display: block;
  width: 86px;
  height: 42px;
  position: absolute;
  background-color: #ccc;
  z-index: -1;
  border-radius: 4px;
}
input:checked::after{
  background-color: red;
}
<div class="chk">
    <label>
        CheckMe
        <input type="checkbox" id="myCheckBox">
    </label>
</div>

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

Is it possible to use an :after background-image to layer on top of the following element?

Seeking assistance on adding an image as a :after element to a navigation bar. The goal is for the image to cover the top portion of the next section according to the design. I have set the :after element as position: absolute with a top: 100%, but it app ...

Adjust the hue as you scroll

I've been searching for a solution to this issue, but I haven't been able to make it work. My goal is to have the page header change from a transparent background to a red background as the user starts scrolling down the page. $(window).on("s ...

The sub menu in IE 8 does not stay open while hovering over it

My website has a navigation menu with a sub-menu that appears when hovering over the parent element. While this works smoothly on modern browsers, Internet Explorer 8 presents an issue. When hovering over the parent li element in IE 8, the sub-menu is disp ...

Setting the background color for a div in Vue.js when importing HTML

Check out this HTML code snippet <!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Getting Started: Serving Web Content< ...

Height of the Accordion List

I have a code snippet below for an accordion list that I put together. I initially set the height for all the heading boxes to be uniform, but it seems like box A is displaying larger than the others. Can you help me figure out what went wrong? Any suggest ...

"Implementing a function to automatically input a selected value from a dropdown menu into a text field

I'm facing an issue and need some help. I have a form with one select field and one text field. What I want is for the text field to display a value corresponding to the option selected in the select field. For example, if I choose "B" from the select ...

What is the correct way to denote a CSS class in SASS syntax?

Can you show me how to code this in SASS? .solo:hover > .solo-pane, .solo-pane.active, .solo-pane.lighten { opacity: 0.5; } I'm having trouble separating the classes using commas. ...

Pan motion gesture above HTML components

Is it possible to create a hovering effect over elements in a container using a pan gesture? https://i.sstatic.net/E6G56.gif Here's the HTML code: <div class="container"> <div class="item"></div> <div class="item"></div ...

My custom styles no longer seem to be applying after upgrading Angular Material from version 14 to 15. What could be causing this issue

Having some challenges with the migration from Angular 14 to Angular 15 when it comes to overriding material UI elements and themes. Looking for blog posts or documentation that can provide guidance on how to smoothly transition. Specifically, experiencin ...

The content entered into the text area does not appear as it was originally typed

Users have reported an issue with the input area - when they update the text, it does not display as expected. For instance, new lines are not being shown. Here is a snapshot of what the user typed in: https://i.sstatic.net/JK0OQ.png However, after upda ...

What are some ways to implement smooth scrolling when a navigation link is clicked?

I have a total of 3 links in my navigation bar and every time they are clicked, I want the page to smoothly scroll down to their designated section on the webpage. Although I have already set up the anchors, I lack experience in scripting to create the smo ...

Generate a div element that is positioned at the exact same location as the image

I have successfully created an interactive image slider. When a user clicks on an image, I am using JavaScript to dynamically generate and display a div with additional text content. However, I am facing an issue where the newly created div appears on the ...

if the condition is not met, proceed to the alternate template eventually

Hey there, I'm facing an issue with my code that resembles something like this: <ng-container *ngIf="firstCondition; else Farewell"> <ng-container *ngIf="innerContainer"> <div class="Hello Message"> {{HelloMessa ...

Guide on implementing Content Security Policy (CSP) for smartsupp chat in Yii2

Currently, I am utilizing the Yii2 https://github.com/tomlutzenberger/yii2-smartsupp-chat widget and it is functioning quite well. However, I have encountered an issue where it is unable to record videos on their website. The solution suggested by them is ...

Streamlining Tailwind CSS styles in your React/Next.js components for maximum efficiency

Since implementing Tailwind CSS in my React/Next.js project, I've noticed a decrease in maintainability compared to using traditional CSS or styled-components. Previously, I could easily consolidate style changes, but now I find myself duplicating cla ...

Transfer data from a Django template populated with items from a forloop using Ajax to a Django view

Struggling to implement a click and populate div with ajax in my django e-commerce app. The function involves clicking on a category in the men's page which then populates another div. gender.html {%for cate in cat%} <a href="javascript:getcat()" ...

Differences Between Mobile and Desktop Browser Media Queries

As I work on creating a responsive website, I have come across various examples of sites that adapt well to both desktop and mobile browsers. Currently, my stylesheet setup includes different media queries for various screen sizes. However, I've notic ...

Adjusting the text color of cells in a table based on their values using Ruby on Rails

I have a cell within a table that is formatted like this: <td><%= play_result.timestamp.strftime("%H:%M:%S") + ' ' + play_result.status + ':' + ' ' + '[' + play_result.host + ']' + ' ' ...

Differentiate the items within a list containing identical divs using JavaScript

Currently, I am expanding my knowledge in HTML, CSS, and JS by incorporating Angular and JQuery. In one of my projects, there is a div labeled "eventBoxes" where multiple divs known as "eventBox" can be added. I have created a template for the eventBox i ...

Include a link in the email body without displaying the URL

My concern revolves around displaying a shortened text instead of the full link within an email. When the recipient clicks on "Open Link," they should be redirected to the URL specified. The text "Open Link" must appear in bold. My current development fram ...