Tips on designing checkboxes with CSS

Can someone help me figure out how to style a checkbox using the code below?

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />

I've tried applying this style but it doesn't seem to work. The checkbox is still showing its default style. Any suggestions on how to make the specified styles show up properly?

Answer №1

UPDATE:

Before the widespread availability of CSS 3, creating custom checkbox replacements required JavaScript. However, in modern browsers like Internet Explorer 9 and later, it is now easier to style checkboxes using CSS without the need for JavaScript.

For more information on how to create custom form checkboxes with CSS, check out these helpful links:

  • Creating Custom Form Checkboxes with Just CSS
  • Easy CSS Checkbox Generator
  • Stuff You Can Do With The Checkbox Hack
  • Implementing Custom Checkboxes and Radio Buttons with CSS3
  • How to Style a Checkbox With CSS

Although you still can't directly apply styles to the checkbox element itself, it is now possible to hide the default checkbox and replace it with a styled element using only CSS. This method allows you to reflect the checked status of the box using the :checked selector.


OLDER ANSWER

If you're interested in styling checkboxes, this article discusses the challenges that come with browser compatibility when trying to style checkboxes. Some browsers may always display the default checkbox despite styling attempts.

One workaround is using JavaScript to overlay an image on the checkbox and have clicks on the image trigger the checkbox check. Users without JavaScript enabled would see the default checkbox.

Additionally, here's a useful script that hides the real checkbox, replaces it with a styled span, and handles click events accordingly.

Answer №2

If you want to create a unique and stylish checkbox design, consider using the :after and :before pseudo classes. The great thing about this method is that you don't have to clutter your DOM with additional elements, just utilize the standard checkbox.

Please note that this approach works best on compatible browsers like Chrome and Safari, as some browsers may not fully support the use of :after and :before on input elements. Despite limitations in Firefox and Internet Explorer, the checkboxes will still work but appear unstyled. Hopefully, future updates will address this issue without requiring vendor prefixes.

This solution is intended for WebKit browsers only, including Chrome, Safari, and mobile browsers.

Check out an Example Fiddle Here

$(function() {
  $('input').change(function() {
    $('div').html(Math.random());
  });
});
/* Main Classes */
.myinput[type="checkbox"]:before {
  position: relative;
  display: block;
  width: 11px;
  height: 11px;
  border: 1px solid #808080;
  content: "";
  background: #FFF;
}

... (CSS styles continue)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table style="width:100%">
  <tr>
    ... (table rows continue)
  </tr>
  <tr>
    ... (additional table rows)
  </tr>
</table>

Explore a Bonus Webkit Style Flipswitch Fiddle

$(function() {
  var f = function() {
    $(this).next().text($(this).is(':checked') ? ':checked' : ':not(:checked)');
  };
  $('input').change(f).trigger('change');
});
body {
  font-family: arial;
}

.flipswitch {
  position: relative;
  background: white;
  width: 120px;
  height: 40px;
  -webkit-appearance: initial;
  ... (continued CSS styles)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<h2>Webkit friendly mobile-style checkbox/flipswitch</h2>
<input type="checkbox" class="flipswitch" /> &nbsp;
<span></span>
<br>
<input type="checkbox" checked="checked" class="flipswitch" /> &nbsp;
<span></span>

Answer №3

Updated Information (as of Jan 2021)

The original question and answer were posted about 5 years ago, so it's time for a refresh.

When it comes to styling checkboxes, there are multiple approaches to consider:

  1. You must hide the default checkbox control provided by the browser because CSS cannot fully override its styling.

  2. Even with the checkbox hidden, you still need to detect and toggle its checked state.

  3. To visually represent the checked state, you'll need to style a new element.

Possible Solutions

There are various ways to achieve this task, and while CSS3 pseudo-elements are often recommended, the best approach depends on your specific needs. Here is one suggested method:

  1. Enclose your checkbox within a label tag. This allows the user to click anywhere within the label to toggle the checkbox.

  2. Hide the actual checkbox itself.

  3. Add a new element after the checkbox that can be styled to indicate the checked state. Placing it after the checkbox enables CSS selection based on the :checked state.

Implementation (with Code Example)

label input {
  visibility: hidden;/* <-- Hide the default checkbox. The rest is to hide and allow tabbing, which display:none prevents */
  display: block;
  height: 0;
  width: 0;
  position: absolute;
  overflow: hidden;
}
label span {/* <-- Style the artificial checkbox */
  height: 10px;
  width: 10px;
  border: 1px solid grey;
  display: inline-block;
}
[type=checkbox]:checked + span {/* <-- Style its checked state */
  background: black;
}
<label>
  <input type='checkbox'>
  <span></span>
  Checkbox label text
</label>

Enhancement (Using Icons)

If you want to include icons like a tick or cross without using background images, CSS3 pseudo-elements can be helpful. These allow you to add Unicode icons representing different states or use a font icon library like Font Awesome (remember to set the correct font-family).

label input {
  display: none; /* Hide the default checkbox */
}

/* Style the artificial checkbox */
label span {
  height: 10px;
  width: 10px;
  border: 1px solid grey;
  display: inline-block;
  position: relative;
}

/* Style its checked state with a ticked icon */
[type=checkbox]:checked + span:before {
  content: '\2714';
  position: absolute;
  top: -5px;
  left: 0;
}
<label>
  <input type='checkbox'>
  <span></span>
  Checkbox label text
</label>

Answer №4

One innovative way to achieve this effect is by utilizing only CSS. By manipulating the label element, we can create a visually appealing design for checkboxes. It's worth noting that this method may not be compatible with Internet Explorer 8 and earlier versions.

.myCheckbox input {
  position: relative;
  z-index: -9999;
}

.myCheckbox span {
  width: 20px;
  height: 20px;
  display: block;
  background: url("link_to_image");
}

.myCheckbox input:checked + span {
  background: url("link_to_another_image");
}
<label for="test">Label for my styled "checkbox"</label>
<label class="myCheckbox">
  <input type="checkbox" name="test" />
  <span></span>
</label>

Answer №5

Revolutionary approach to accessibility - integrating accent-color

The latest technique involves utilizing the innovative accent-color property while ensuring a proper contrast ratio of 3:1 for enhanced accessibility. This method is effective even with radio buttons.

.red-input {
    accent-color: #9d3039;
    height: 20px; /* can be omitted */
    width: 20px; /* can be omitted */
}
<input class="red-input" type="checkbox" />

<!-- Example of Radio button -->
<input class="red-input" type="radio" />


Traditional solution, recommended only when advanced customization is necessary:

Many solutions overlook accessibility concerns and end up breaching WCAG guidelines in multiple ways. Alongside custom checkboxes, providing customized radio buttons is advisable in most scenarios.

Code Demos:

Lagging behind in time but still challenging in 2019, 2020, 2021, I introduce three accessible and user-friendly solutions.

All these solutions are devoid of JavaScript, ensure accessibility, and eliminate reliance on external libraries*...

To swiftly implement any of these styles, copy the style sheet from the demos, tweak the color codes in the CSS as needed, and seamlessly integrate them into your project. Custom SVG checkmark icons can also be included for checkboxes. Ample comments are provided for non-CSS individuals.

If text wrapping issues arise beneath checkbox or radio input within a cramped container due to lengthy text, consider switching to div elements like this.

Detailed Explanation: My quest was to find a viable solution that adheres to WCAG recommendations, excludes JavaScript or third-party frameworks, maintains smooth keyboard navigation functionality, incorporates focus events, caters to disabled checkboxes—whether checked or unchecked—, and finally offers limitless customization possibilities for checkbox appearance using varied properties like background-color, border-radius, svg backgrounds, etc.

Inspirations were drawn from this guide shared by @Jan Turoň which led me to formulate my own satisfactory solution. The radio button demonstration shares resemblance with the checkbox logic to enable compatibility.

I'm continuously learning about accessibility nuances, so feedback pointing out oversights is highly appreciated for rectification.

This snippet illustrates my checkbox implementation:

input[type="checkbox"] {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

/* Label's text color */
input[type="checkbox"]+span {
  cursor: pointer;
  font: 16px sans-serif;
  color: black;
}

/* Unchecked checkbox style */
input[type="checkbox"]+span:before {
  content: '';
  border: 1px solid grey;
  border-radius: 3px;
  display: inline-block;
  width: 16px;
  height: 16px;
  margin-right: 0.5em;
  margin-top: 0.5em;
  vertical-align: -2px;
}

/* Styling for checked checkbox (green background here #e7ffba, adjustable to desired color) */
input[type="checkbox"]:checked+span:before {
  background-image: url('https://cdnjs.cloudflare.com/ajax/libs/ionicons/4.5.6/collection/build/ionicons/svg/ios-checkmark.svg');
  background-repeat: no-repeat;
  background-position: center;
  background-size: 25px;
  border-radius: 2px;
  background-color: #e7ffba;
  color: white;
}

/* Dotted border around focused checkbox */
input[type="checkbox"]:focus+span:before,
input[type="checkbox"]:not(:disabled)+span:hover:before {
  box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1);
  outline-color: transparent;
  outline-width: 2px;
  outline-style: dotted;
}

/* Disabled checkbox styles */
input[type="checkbox"]:disabled+span {
  cursor: default;
  color: black;
  opacity: 0.5;
}

/* Specific fiddle styles that may not be essential */
body {
  padding: 1em;
}
h1 {
  font-size: 18px;
}
<h1>
  NOTE: Modify the URL for background-image path in CSS depending on chosen SVG source. The current one was sourced from an internet search for a checkmark icon CDN
</h1>

<p>Easily adjust background color, checkbox symbol, border-radius, etc.</p>

<label>
  <input type="checkbox">
  <span>Try tabbing and space usage</span>
</label>

<br>

<label>
  <input type="checkbox" checked disabled>
  <span>Inactive Checked Checkbox</span>
</label>

<br>

<label>
  <input type="checkbox" disabled>
  <span>Disabled Checkbox</span>
</label>
<br>

<label>
  <input type="checkbox">
  <span>Standard Checkbox</span>
</label>

<br>

<label>
  <input type="checkbox">
  <span>Another Standard Checkbox</span>
</label>

Answer №6

I have found a great solution for customizing the appearance of checkboxes and radio buttons by using pseudo elements :before and :after. It works like magic!

To learn more about this technique, check out this link.

If you want to see the code in action, visit this CODEPEN demo.

Here are the steps:

  1. Start by hiding the default checkbox using CSS rules such as visibility:hidden, opacity:0, or position:absolute;left:-9999px.
  2. Create a custom checkbox using the :before element and provide an empty space or non-breaking space '\00a0';
  3. When the checkbox is checked (:checked state), display a checkmark unicode content: "\2713";
  4. Add styles for focus to make the checkbox accessible;
  5. You're done!

Below is an example of how I implemented this technique:

.box {
  background: #666666;
  color: #ffffff;
  width: 250px;
  padding: 10px;
  margin: 1em auto;
}
p {
  margin: 1.5em 0;
  padding: 0;
}
input[type="checkbox"] {
  visibility: hidden;
}
label {
  cursor: pointer;
}
input[type="checkbox"] + label:before {
  border: 1px solid #333;
  content: "\00a0";
  display: inline-block;
  font: 16px/1em sans-serif;
  height: 16px;
  margin: 0 .25em 0 0;
  padding: 0;
  vertical-align: top;
  width: 16px;
}
input[type="checkbox"]:checked + label:before {
  background: #fff;
  color: #333;
  content: "\2713";
  text-align: center;
}
input[type="checkbox"]:checked + label:after {
  font-weight: bold;
}

input[type="checkbox"]:focus + label::before {
    outline: rgb(59, 153, 252) auto 5px;
}
<div class="content">
  <div class="box">
    <p>
      <input type="checkbox" id="c1" name="cb">
      <label for="c1">Option 01</label>
    </p>
    <p>
      <input type="checkbox" id="c2" name="cb">
      <label for="c2">Option 02</label>
    </p>
    <p>
      <input type="checkbox" id="c3" name="cb">
      <label for="c3">Option 03</label>
    </p>
  </div>
</div>

For a more stylish implementation using :before and :after:

body{
  font-family: sans-serif;  
}

.container {
    margin-top: 50px;
    margin-left: 20px;
    margin-right: 20px;
}
.checkbox {
    width: 100%;
    margin: 15px auto;
    position: relative;
    display: block;
}

.checkbox input[type="checkbox"] {
    width: auto;
    opacity: 0.00000001;
    position: absolute;
    left: 0;
    margin-left: -20px;
}
.checkbox label {
    position: relative;
}
.checkbox label:before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    margin: 4px;
    width: 22px;
    height: 22px;
    transition: transform 0.28s ease;
    border-radius: 3px;
    border: 2px solid #7bbe72;
}
.checkbox label:after {
  content: '';
    display: block;
    width: 10px;
    height: 5px;
    border-bottom: 2px solid #7bbe72;
    border-left: 2px solid #7bbe72;
    -webkit-transform: rotate(-45deg) scale(0);
    transform: rotate(-45deg) scale(0);
    transition: transform ease 0.25s;
    will-change: transform;
    position: absolute;
    top: 12px;
    left: 10px;
}
.checkbox input[type="checkbox"]:checked ~ label::before {
    color: #7bbe72;
}

.checkbox input[type="checkbox"]:checked ~ label::after {
    -webkit-transform: rotate(-45deg) scale(1);
    transform: rotate(-45deg) scale(1);
}

.checkbox label {
    min-height: 34px;
    display: block;
    padding-left: 40px;
    margin-bottom: 0;
    font-weight: normal;
    cursor: pointer;
    vertical-align: sub;
}
.checkbox label span {
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
}
.checkbox input[type="checkbox"]:focus + label::before {
    outline: 0;
}
<div class="container"> 
  <div class="checkbox">
     <input type="checkbox" id="checkbox" name="" value="">
     <label for="checkbox"><span>Checkbox</span></label>
  </div>

  <div class="checkbox">
     <input type="checkbox" id="checkbox2" name="" value="">
     <label for="checkbox2"><span>Checkbox</span></label>
  </div>
</div>

Answer №7

I used to follow SW4's advice from this post. However, I now believe that Volomike's answer in this response is the best solution (please see my comment for an improvement suggestion). Keep reading if you're interested in exploring different approaches mentioned in this answer.


To begin with, consider hiding the checkbox and replacing it with a custom span, as shown in the following HTML:

<label>
  <input type="checkbox">
  <span>send newsletter</span>
</label>

The use of a label allows users to click the text without needing to link it via the "for-id" attribute. However,

Avoid using visibility: hidden or display: none

While these methods may work when clicking or tapping, they are not efficient ways to interact with checkboxes. Some individuals prefer using the Tab key to move focus and the Space key to activate, but hiding the checkbox in this manner disables such functionality. For longer forms, incorporating attributes like tabindex or accesskey can help prevent strain on the user’s wrists. Additionally, a well-styled checkbox should mimic the system's hover effects.

In cobberboy's response, Font Awesome is recommended for its scalability compared to bitmap images. When using the provided HTML structure, the following CSS rules are suggested:

  1. Hide checkboxes

     input[type="checkbox"] {
       position: absolute;
       opacity: 0;
       z-index: -1;
     }
    

    The use of a negative z-index ensures that the custom checkbox graphics cover the original checkbox entirely. It's advised against using left: -999px as it might not be universally applicable across all layouts. Alternatively, Bushan wagh's solution provides a more foolproof method for hiding checkboxes while preserving tabindex functionality. Both approaches are somewhat unconventional hacks, with the preferred modern technique being appearance: none, as mentioned in Joost's answer:

     input[type="checkbox"] {
       appearance: none;
       -webkit-appearance: none;
       -moz-appearance: none;
     }
    
  2. Style checkbox label

     input[type="checkbox"] + span {
       font: 16pt sans-serif;
       color: #000;
     }
    
  3. Add checkbox skin

     input[type="checkbox"] + span:before {
       font: 16pt FontAwesome;
       content: '\00f096';
       display: inline-block;
       width: 16pt;
       padding: 2px 0 0 3px;
       margin-right: 0.5em;
     }
    

The character \00f096 corresponds to Font Awesome's square-o, and the padding adjustments ensure an even dotted outline upon focusing (as described below).

  1. Add checked checkbox skin

     input[type="checkbox"]:checked + span:before {
       content: '\00f046';
     }
    

The character \00f046 represents Font Awesome's check-square-o, which has a different width than square-o, hence the specified width style above.

  1. Add focus outline

     input[type="checkbox"]:focus + span:before {
       outline: 1px dotted #aaa;
     }
    

    Note that Safari lacks support for this feature (refer to @Jason Sankey's comment), with a specific CSS solution outlined in this answer solely for Safari browsers.

  2. Set gray color for disabled checkbox

     input[type="checkbox"]:disabled + span {
       color: #999;
     }
    
  3. Apply hover shadow on non-disabled checkbox

     input[type="checkbox"]:not(:disabled) + span:hover:before {
       text-shadow: 0 1px 2px #77F;
     }
    

Explore the interactive example on JS Fiddle

Hover over the checkboxes, navigate using Tab and Shift+Tab, and utilize the Space key for toggling functionality.

Answer №8

The CSS Basic User Interface Module Level 4 introduces a new feature called accent-color, making it easier to customize styles:

input {
    accent-color: rebeccapurple;
}
<input type="checkbox" />

You can specify any CSS color value (e.g. named, hex code) for the accent-color property, and it will be applied accordingly.

Currently supported in Chrome (v93+), Edge (v93+), Firefox (v92+), Opera (v79+), and Safari (v15.4+).

Note: Some browsers may not fully support alpha channel values via rgba(). Refer to MDN Browser Compatibility for details.

Answer №9

By using pure CSS without any fancy :before or :after tricks, no transforms needed, you have the ability to disable the default appearance and then customize it with an inline background image as demonstrated in the code snippet below. This method is compatible with Chrome, Firefox, Safari, and the latest version of Edge (Chromium Edge).

INPUT[type=checkbox]:focus
{
    outline: 1px solid rgba(0, 0, 0, 0.2);
}

INPUT[type=checkbox]
{
    background-color: #DDD;
    border-radius: 2px;
    appearance: none;
    -webkit-appearance: none;
    -moz-appearance: none;
    width: 17px;
    height: 17px;
    cursor: pointer;
    position: relative;
    top: 5px;
}

INPUT[type=checkbox]:checked
{
    background-color: #409fd6;
    background: #409fd6 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
<form>
  <label><input type="checkbox"> I Agree To Terms &amp; Conditions</label>
</form>

Answer №10

Easy-to-use and fully customizable solution

After extensive research and testing, I stumbled upon a simple and highly customizable solution that is easy to implement and modify. This solution offers the following benefits:

  1. No external libraries or files required
  2. No need to insert additional HTML into your page
  3. No necessity to alter checkbox names and IDs

To effortlessly transform the appearance of all checkboxes on your page, simply add the following CSS snippet at the top:

https://i.stack.imgur.com/hclvc.jpg

input[type=checkbox] {
  transform: scale(1.5);
}

input[type=checkbox] {
  width: 30px;
  height: 30px;
  margin-right: 8px;
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
}

input[type=checkbox]:after,
input[type=checkbox]::after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  margin-left: 10px;
  padding-bottom: 5px;
  color: #00BFF0;
  width: 22px;
  height: 25px;
  visibility: visible;
  border: 1px solid #00BFF0;
  padding-left: 3px;
  border-radius: 5px;
}

input[type=checkbox]:checked:after,
input[type=checkbox]:checked::after {
  content: "\2714";
  padding: -5px;
  font-weight: bold;
}
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox</label>

Answer №11

Enhance the appearance of checkboxes with a clever technique utilizing the label element as illustrated below:

.checkbox > input[type=checkbox] {
  visibility: hidden;
}

.checkbox {
  position: relative;
  display: block;
  width: 80px;
  height: 26px;
  margin: 0 auto;
  background: #FFF;
  border: 1px solid #2E2E2E;
  border-radius: 2px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
}

.checkbox:after {
  position: absolute;
  display: inline;
  right: 10px;
  content: 'no';
  color: #E53935;
  font: 12px/26px Arial, sans-serif;
  font-weight: bold;
  text-transform: capitalize;
  z-index: 0;
}

.checkbox:before {
  position: absolute;
  display: inline;
  left: 10px;
  content: 'yes';
  color: #43A047;
  font: 12px/26px Arial, sans-serif;
  font-weight: bold;
  text-transform: capitalize;
  z-index: 0;
}

.checkbox label {
  position: absolute;
  display: block;
  top: 3px;
  left: 3px;
  width: 34px;
  height: 20px;
  background: #2E2E2E;
  cursor: pointer;
  transition: all 0.5s linear;
  -webkit-transition: all 0.5s linear;
  -moz-transition: all 0.5s linear;
  border-radius: 2px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  z-index: 1;
}

.checkbox input[type=checkbox]:checked + label {
  left: 43px;
}
<div class="checkbox">
  <input id="checkbox1" type="checkbox" value="1" />
  <label for="checkbox1"></label>
</div>

Check out this FIDDLE providing an interactive demo of the code above. Please note that some CSS may not work in older browsers, but innovative JavaScript solutions can also be explored!

Answer №12

To circumvent the need for additional markup, you can utilize this method which functions across various platforms except for IE by adjusting the CSS appearance:

input[type="checkbox"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;

  /* Styling checkbox */
  width: 16px;
  height: 16px;
  background-color: red;
}

input[type="checkbox"]:checked {
  background-color: green;
}
<input type="checkbox" />

Answer №13

Recently, I stumbled upon an intriguing solution to the issue at hand.

You can utilize appearance: none; to disable the default styling of the checkbox and then create your own custom style, as detailed here (Example 4).

input[type=checkbox] {
  width: 23px;
  height: 23px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  margin-right: 10px;
  background-color: #878787;
  outline: 0;
  border: 0;
  display: inline-block;
  -webkit-box-shadow: none !important;
  -moz-box-shadow: none !important;
  box-shadow: none !important;
}

input[type=checkbox]:focus {
  outline: none;
  border: none !important;
  -webkit-box-shadow: none !important;
  -moz-box-shadow: none !important;
  box-shadow: none !important;
}

input[type=checkbox]:checked {
  background-color: green;
  text-align: center;
  line-height: 15px;
}
<input type="checkbox">

Unfortunately, support for the appearance property is quite limited across different browsers. Based on my testing, I found that only Opera and Chrome displayed the desired results correctly. However, this method could be the way forward for simplicity until better browser support becomes available or if you specifically target Chrome/Opera.

JSFiddle Demo

"Can I use?" Browser Support Info

Answer №14

My preference lies with utilizing icon fonts like FontAwesome due to their ease of color modification through CSS and excellent scalability on high pixel-density devices. Below is a variant created purely in CSS using similar techniques as the ones mentioned earlier.

(The image below is static for visualization; refer to the interactive JSFiddle version.)

Similar to other solutions, this one incorporates the label element with an adjacent span that contains the checkbox character.

span.bigcheck-target {
  font-family: FontAwesome; /* Utilizing an icon font for the checkbox */
}

input[type='checkbox'].bigcheck {
  position: relative;
  left: -999em; /* Hiding the actual checkbox */
}

input[type='checkbox'].bigcheck + span.bigcheck-target:after {
  content: "\f096"; /* Represents an open square (fa-square-o) in FontAwesome */
}

input[type='checkbox'].bigcheck:checked + span.bigcheck-target:after {
  content: "\f046"; /* Denotes a checked box (fa-check-square-o) in FontAwesome */
}

/* ==== Optional - custom colors and padding for aesthetic appeal === */
body {
  background-color: #2C3E50;
  color: #D35400;
  font-family: sans-serif;
  font-weight: 500;
  font-size: 4em; /* Adjust size as needed */
}

span.bigcheck {
  display: block;
  padding: 0.5em;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

<span class="bigcheck">
  <label class="bigcheck">
    Cheese
    <input type="checkbox" class="bigcheck" name="cheese" value="yes" />
    <span class="bigcheck-target"></span>
  </label>
</span>

Check out the JSFiddle link for further details.

Answer №15

Here's How I Solved It

input[type="checkbox"] {
  cursor: pointer;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: 0;
  background: lightgray;
  height: 16px;
  width: 16px;
  border: 1px solid white;
}

input[type="checkbox"]:checked {
  background: #2aa1c0;
}

input[type="checkbox"]:hover {
  filter: brightness(90%);
}

input[type="checkbox"]:disabled {
  background: #e6e6e6;
  opacity: 0.6;
  pointer-events: none;
}

input[type="checkbox"]:after {
  content: '';
  position: relative;
  left: 40%;
  top: 20%;
  width: 15%;
  height: 40%;
  border: solid #fff;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  display: none;
}

input[type="checkbox"]:checked:after {
  display: block;
}

input[type="checkbox"]:disabled:after {
  border-color: #7b7b7b;
}
<input type="checkbox><br>
<input type="checkbox" checked><br>
<input type="checkbox" disabled><br>
<input type="checkbox" disabled checked><br>

Answer №16

To ensure that your styles are applied properly without any default styling, you can utilize the appearance: none property on modern browsers:

input[type=checkbox] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  display: inline-block;
  width: 2em;
  height: 2em;
  border: 1px solid gray;
  outline: none;
  vertical-align: middle;
}

input[type=checkbox]:checked {
  background-color: blue;
}

Answer №17

Check out this effortless CSS solution that doesn't require any jQuery or JavaScript.

I've opted for FontAwseome icons in this example, but feel free to use any image of your choice.

input[type=checkbox] {
  display: inline-block;
  font-family: FontAwesome;
  font-style: normal;
  font-weight: normal;
  line-height: 1;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  visibility: hidden;
  font-size: 14px;
}

input[type=checkbox]:before {
  content: @fa-var-square-o;
  visibility: visible;
  /*font-size: 12px;*/
}

input[type=checkbox]:checked:before {
  content: @fa-var-check-square-o;
}

Answer №18

After conducting some research, I have found a simple method for styling checkboxes. You can achieve this by utilizing the :after and :checked:after CSS selectors to customize the design according to your preferences.

body{
  background: #DDD;
}
span{
  margin-left: 30px;
}
input[type=checkbox] {
    cursor: pointer;
    font-size: 17px;
    visibility: hidden;
    position: absolute;
    top: 0;
    left: 0;
    transform: scale(1.5);
}

input[type=checkbox]:after {
    content: " ";
    background-color: #fff;
    display: inline-block;
    color: #00BFF0;
    width: 14px;
    height: 19px;
    visibility: visible;
    border: 1px solid #FFF;
    padding: 0 3px;
    margin: 2px 0;
    border-radius: 8px;
    box-shadow: 0 0 15px 0 rgba(0,0,0,0.08), 0 0 2px 0 rgba(0,0,0,0.16);
}

input[type=checkbox]:checked:after {
    content: "\2714";
    display: unset;
    font-weight: bold;
}
<input type="checkbox"> <span>Select Text</span>

Answer №19

Revamp the look of checkboxes using only CSS, no need for JavaScript or HTML edits:

.form input[type="checkbox"]:before {
  display: inline-block;
  font: normal normal normal 14px/1 FontAwesome;
  font-size: inherit;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  content: "\f096";
  opacity: 1 !important;
  margin-top: -25px;
  appearance: none;
  background: #fff;
}

.form input[type="checkbox"]:checked:before {
  content: "\f046";
}

.form input[type="checkbox"] {
  font-size: 22px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<form class="form">
  <input type="checkbox" />
</form>

Answer №20

Wow! Dealing with all these workarounds has made me realize that styling the HTML checkbox can be quite challenging.

Just a heads up, this isn't a CSS solution. I thought I'd share the workaround I came up with in case it could be useful to someone else.


My solution involved using the canvas element in HTML5.

The benefit of this approach is that you can avoid using external images and potentially save on bandwidth.

The downside is that if a browser is unable to render the canvas correctly, there's no fallback option. However, this might not be as big of an issue in 2017.

Update

I found the original code to be quite messy, so I decided to give it a revamp.

Object.prototype.create = function(args){
    var newObj = Object.create(this);

    newObj.constructor(args || null);

    return newObj;
}

var Checkbox = Object.seal({
    width: 0,
    height: 0,
    state: 0,
    document: null,
    parent: null,
    canvas: null,
    ctx: null,

    /*
     * args:
     * name      default             desc.
     *
     * width     15                  width
     * height    15                  height
     * document  window.document     explicit document reference
     * target    this.document.body  target element to insert checkbox into
     */
    constructor: function(args){
        if(args === null)
            args = {};

        this.width = args.width || 15;
        this.height = args.height || 15;
        this.document = args.document || window.document;
        this.parent = args.target || this.document.body;
        this.canvas = this.document.createElement("canvas");
        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.addEventListener("click", this.ev_click(this), false);
        this.parent.appendChild(this.canvas);
        this.draw();
    },

    ev_click: function(self){
        return function(unused){
            self.state = !self.state;
            self.draw();
        }
    },

    draw_rect: function(color, offset){
        this.ctx.fillStyle = color;
        this.ctx.fillRect(offset, offset,
                this.width - offset * 2, this.height - offset * 2);
    },

    draw: function(){
        this.draw_rect("#CCCCCC", 0);
        this.draw_rect("#FFFFFF", 1);

        if(this.is_checked())
            this.draw_rect("#000000", 2);
    },

    is_checked: function(){
        return !!this.state;
    }
});

Check out the live demo here.

The updated version utilizes prototypes and differential inheritance to create an efficient system for generating checkboxes. To create a checkbox:

var myCheckbox = Checkbox.create();

This will instantly add the checkbox to the DOM and set up the events. To check if a checkbox is ticked:

myCheckbox.is_checked(); // Returns true if checked, otherwise false

It's also worth noting that I eliminated the loop.

Update 2

In my previous update, I forgot to mention that utilizing the canvas offers more benefits than just customizing the checkbox appearance. You can even create checkboxes with multiple states, if desired.

Object.prototype.create = function(args){
    var retObj = Object.create(this);

    retObj.constructor(args || null);

    return retObj;
}

Object.prototype.extend = function(newObj){
    var oldObj = Object.create(this);

    for(property in newObj)
        oldObj[property] = newObj[property];

    return Object.seal(oldObj);
}

var Checkbox = Object.seal({
    width: 0,
    height: 0,
    state: 0,
    document: null,
    parent: null,
    canvas: null,
    ctx: null,

    /*
     * args:
     * name      default             desc.
     *
     * width     15                  width
     * height    15                  height
     * document  window.document     explicit document reference
     * target    this.document.body  target element to insert checkbox into
     */
    constructor: function(args){
        if(args === null)
            args = {};

        this.width = args.width || 15;
        this.height = args.height || 15;
        this.document = args.document || window.document;
        this.parent = args.target || this.document.body;
        this.canvas = this.document.createElement("canvas");
        this.ctx = this.canvas.getContext('2d');

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.canvas.addEventListener("click", this.ev_click(this), false);
        this.parent.appendChild(this.canvas);
        this.draw();
    },

    ev_click: function(self){
        return function(unused){
            self.state = (self.state + 1) % 3;
            self.draw();
        }
    },

    draw_rect: function(color, offsetX, offsetY){
        this.ctx.fillStyle = color;
        this.ctx.fillRect(offsetX, offsetY,
                this.width - offsetX * 2, this.height - offsetY * 2);
    },

    draw: function(){
        this.draw_rect("#CCCCCC", 0, 0);
        this.draw_rect("#FFFFFF", 1, 1);
        this.draw_state();
    },

    draw_state: function(){
        if(this.is_checked())
            this.draw_rect("#000000", 2, 2);

        if(this.is_partial())
            this.draw_rect("#000000", 2, (this.height - 2) / 2);
    },

    is_checked: function(){
        return this.state == 1;
    },

    is_partial: function(){
        return this.state == 2;
    }
});

var Checkbox3 = Checkbox.extend({
    ev_click: function(self){
        return function(unused){
            self.state = (self.state + 1) % 3;
            self.draw();
        }
    },

    draw_state: function(){
        if(this.is_checked())
            this.draw_rect("#000000", 2, 2);

        if(this.is_partial())
            this.draw_rect("#000000", 2, (this.height - 2) / 2);
    },

    is_partial: function(){
        return this.state == 2;
    }
});

I made slight adjustments to the previous Checkbox implementation to make it more versatile, allowing for extension with a 3-state checkbox. Check out the demo here. As you can see, it already offers more functionality than a standard checkbox.

When deciding between JavaScript and CSS, consider these points.

Original Code

Live Demo

First, prepare a canvas:

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d'),
    checked = 0; // The state of the checkbox
canvas.width = canvas.height = 15; // Set the width and height of the canvas
document.body.appendChild(canvas);
document.body.appendChild(document.createTextNode(' Togglable Option'));

Next, establish a method for updating the canvas automatically:

(function loop(){
  // Draws a border
  ctx.fillStyle = '#ccc';
  ctx.fillRect(0,0,15,15);
  ctx.fillStyle = '#fff';
  ctx.fillRect(1, 1, 13, 13);
  // Fills in canvas if checked
  if(checked){
    ctx.fillStyle = '#000';
    ctx.fillRect(2, 2, 11, 11);
  }
  setTimeout(loop, 1000/10); // Refresh 10 times per second
})();

Lastly, make it interactive. Fortunately, it's straightforward:

canvas.onclick = function(){
  checked = !checked;
}

This may cause issues in IE due to its peculiar event handling model in JavaScript.


I hope this guide proves helpful to someone; it certainly met my requirements.

Answer №21

Enhancing Checkbox Styling with SCSS / SASS

A Fresh and Improved Approach

If you are familiar with SCSS (or can easily switch to SASS), this method will provide a modern solution for styling your checkboxes. The idea is to create an element adjacent to the checkbox that can be styled according to the checkbox state. Below is the code snippet to achieve this:

label.checkbox {
  input[type="checkbox"] {
    visibility: hidden;
    display: block;
    height: 0;
    width: 0;
    position: absolute;
    overflow: hidden;

    &:checked + span {
      background: $accent;
    }
  }

  span {
    cursor: pointer;
    height: 15px;
    width: 15px;
    border: 1px solid $accent;
    border-radius: 2px;
    display: inline-block;
    transition: all 0.2s $interpol;
  }
}
<label class="checkbox">
    <input type="checkbox" />
    <span></span>
    Label text
</label>

Answer №22

Check out this minimal and elegant template:

input[type=checkbox] {
  cursor: pointer;
}

input[type=checkbox]:checked:before {
  content: "\2713";
  background: #fffed5;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  font-size: 20px;
  text-align: center;
  line-height: 8px;
  display: inline-block;
  width: 13px;
  height: 15px;
  color: #00904f;
  border: 1px solid #cdcdcd;
  border-radius: 4px;
  margin: -3px -3px;
  text-indent: 1px;
}

input[type=checkbox]:before {
  content: "\202A";
  background: #ffffff;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);
  font-size: 20px;
  text-align: center;
  line-height: 8px;
  display: inline-block;
  width: 13px;
  height: 15px;
  color: #00904f;
  border: 1px solid #cdcdcd;
  border-radius: 4px;
  margin: -3px -3px;
  text-indent: 1px;
}
<input type="checkbox" checked="checked">checked1<br>
<input type="checkbox">unchecked2<br>
<input type="checkbox" checked="checked" id="id1">
<label for="id1">checked2+label</label><br>
<label for="id2">unchecked2+label+rtl</label>
<input type="checkbox" id="id2">
<br>

https://jsfiddle.net/rvgccn5b/

Answer №23

One approach that I find to be quite simple is to style a label element and hide the associated checkbox.

Here's how you can achieve this using HTML:

<input type="checkbox" id="first" />
<label for="first">&nbsp;</label>

For styling with CSS, you can use the following code:

checkbox {
  display: none;
}

checkbox + label {
  /* Style for unchecked checkbox */
  width: 16px;
  height: 16px;
}

checkbox::checked + label,
label.checked {
  /* Style for checked checkbox */
}

Even though the checkbox is hidden, it remains accessible and its value will be included when submitting a form. In older browsers, you may need to utilize JavaScript to toggle the "checked" class on the label, as older versions of Internet Explorer do not support ::checked on the checkbox.

Answer №24

No need for JavaScript or jQuery.

Easily update the style of your checkboxes.

input[type="checkbox"] {
  display: none;
  border: none !important;
  box-shadow: none !important;
}

input[type="checkbox"] + label span {
  background: url("https://i.ibb.co/mG7QRYw/62a9b364a056b98f7e02705a-checkboxunselected.png");
  width: 24px;
  height: 24px;
  display: inline-block;
  vertical-align: middle;
  background-size: 100%;
}

input[type="checkbox"]:checked + label span {
  background: url(https://svgur.com/i/upi.svg);
  width: 24px;
  height: 24px;
  vertical-align: middle;
  background-size: 100%;
}
<input type="checkbox" id="option" />
<label for="option"> <span></span> Click here </label>

Check out this JSFiddle link

Answer №25

Check out this updated design featuring subtle animations and customizable styles:

.checkbox {
    position: relative;
    width: 20px;
    height: 20px;
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    appearance: none;
    background: transparent;
    border: 2px solid #7C7A7D;
    border-radius: 5px;
    margin: 0;
    outline: none;
    transition: 0.5s ease;
    opacity: 0.8;
    cursor: pointer;
}


.checkbox:checked {
    border-color: #7C7A7D;
    background-color: #7C7A7D;
}


.checkbox:checked:before {
   position: absolute;
   left: 2px;
   top: -4px;
   display: block;
   content: '\2713';
   text-align: center;
   color: #FFF;
   font-family: Arial;
   font-size: 14px;
   font-weight: 800;
}


.checkbox:hover {
   opacity: 1.0;
   transform: scale(1.05);
}

Answer №26

Styling Custom Checkbox Using CSS (Specifically for WebKit Browsers like Chrome, Safari, and Mobile browsers)

<input type="checkbox" id="cardAccptance" name="cardAccptance" value="Yes">
<label for="cardAccptance" class="bold"> Save Card for Future Use</label>

CSS:

    /* Styling the custom checkbox */
    
    .checkbox-cu {
        display: block;
        position: relative;
        padding-left: 35px;
        margin-bottom: 0;
        cursor: pointer;
        font-size: 16px;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }
    
    
    /* Hiding the default browser's checkbox */
    
    .checkbox-cu input {
        position: absolute;
        opacity: 0;
        cursor: pointer;
        height: 0;
        width: 0;
    }
    
    
    /* Creating a customized checkbox */
    
    .checkmark {
        position: absolute;
        top: 4px;
        left: 0;
        height: 20px;
        width: 20px;
        background-color: #eee;
        border: 1px solid #999;
        border-radius: 0;
        box-shadow: none;
    }
    
    
    /* Adding grey background color on mouse-over */
    
    .checkbox-cu:hover input~.checkmark {
        background-color: #ccc;
    }
    
    
    /* Applying blue background when checkbox is checked */
    
    .checkbox-cu input:checked~.checkmark {
        background-color: transparent;
    }
    
    
    /* Creating the checkmark/indicator (hidden when not checked) */
    
    .checkmark:after {
        content: "";
        position: absolute;
        display: none;
    }
    
    
    /* Showing the checkmark when checked */
    
    .checkbox-cu input:checked~.checkmark:after {
        display: block;
    }
    
    
    /* Styling the checkmark/indicator */
    
    .checkbox-cu .checkmark::after {
        left: 7px;
        top: 3px;
        width: 6px;
        height: 9px;
        border: solid #28a745;
        border-width: 0 2px 2px 0;
        -webkit-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        transform: rotate(45deg);
        z-index: 100;
    }

Answer №27

Utilizing Materialize alongside a personalized stylesheet can help you create an effect similar to the following:

CSS snippet

.custom_checkbox[type="checkbox"]:checked + span:not(.lever)::before {
  border: 2px solid transparent;
  border-bottom: 2px solid #ffd600;
  border-right: 2px solid #ffd600;
  background: transparent;
}

HTML snippet

<label>
    <input type="checkbox" class="custom_checkbox" />
    <span>Text</span>
</label>

Live Example

JSFiddle demo

Answer №28

Discovering this technique made it possible for me to customize the color of checkboxes

input[type=checkbox] {
  accent-color: red;
}

This method can also be applied to radio buttons.

Answer №29

This method is the most straightforward and allows you to select which checkboxes will have this particular style applied.

CSS:

.check-box input {
  display: none;
}

.check-box span:before {
  content: ' ';
  width: 20px;
  height: 20px;
  display: inline-block;
  background: url("unchecked.png");
}

.check-box input:checked + span:before {
  background: url("checked.png");
}

HTML:

<label class="check-box">
  <input type="checkbox">
  <span>Checkbox Label Text</span>
</label>

Answer №30

Presented here is a CSS/HTML-only version, completely void of jQuery or JavaScript dependency. The HTML structure is simple and clean, accompanied by concise CSS styling.

You can view the JSFiddle demonstration below:

http://jsfiddle.net/v71kn3pr/

Below is the HTML code snippet:

<div id="myContainer">
    <input type="checkbox" name="myCheckbox" id="myCheckbox_01_item" value="red" />
    <label for="myCheckbox_01_item" class="box"></label>
    <label for="myCheckbox_01_item" class="text">I accept the Terms of Use.</label>
</div>

Here is the corresponding CSS markup:

#myContainer {
    outline: black dashed 1px;
    width: 200px;
}
#myContainer input[type="checkbox"][name="myCheckbox"] {
    display: none;
}
/* Additional CSS rules go here */

This HTML/CSS format can be customized to accommodate individual checkboxes or radio buttons, as well as groups of them. Moreover, it allows for checkbox selections via label clicks, ensuring seamless form functionality across various platforms including PHP, ASP.NET, JavaServer Faces, and ColdFusion.

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

What is the best way to preserve the allocated space in the DOM while utilizing CSS display:none?

I have explored the functionalities of display:none and visibility:hidden. However, I need to utilize display:none for a specific reason while still preserving the element's allocated space in the DOM to prevent any impact on adjacent elements. Is thi ...

Using Jquery and CSS to add a class with a 1-second delay when the mouse enters

I have successfully implemented the addClass function in my code, but I'm encountering issues when attempting to use delay or setTimeout functions. It's important to note that I'm avoiding the use of webkit attributes in CSS. If anyone has ...

What is the reason for the presence of additional space below when using x-overflow:hidden?

When I place two spans inside each other and use overflow-x:hidden on the inner span, it results in extra space below the inner span. Why does this happen? <span style="" class="yavbc-color-tip"><span style="">Some text</span></span&g ...

Ways to turn off JavaScript when reaching a certain breakpoint, similar to a media query

I am facing an issue with my <header> and <nav> blocks which are impacted by JavaScript. Is there a way to create a JavaScript solution similar to a media query that would deactivate this JavaScript code if the window width is less than or equa ...

Tips for streamlining the use of hidden and visible div elements with concise code

I have been attempting to use the same code for multiple modules on this page, but none of the methods I've tried seem to be effective. I want to avoid endlessly duplicating existing code. document.addEventListener('DOMContentLoaded', fun ...

"Enhance your website with a sleek Bootstrap navigation system featuring dividers and

Need help with creating a Bootstrap nav menu similar to this design made in Photoshop? Wondering about the best way to position the logo and create dividers between menu items like shown in this image. Here's the HTML code currently being used: & ...

Is there a "Read more" link to expand the content on the page?

I am struggling to figure out why my JavaScript code for toggling between showing more text and less text is not functioning correctly. My goal is for the user to click on the "Show More" button to reveal additional text, and then be able to click on "Show ...

Creating a "return" button for an editing form in AngularJS Datatables with the help of a form directive

Using AngularJS Datatables, I implemented a grid with additional "edit" and "delete" buttons in the last column. How is the grid/table rendered? HTML <!-- Required CSS and JS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/li ...

The DOM assigned a new source to an image

Currently, I am working on a project that involves both jquery and PHP. In this project, users are able to upload images which are then displayed in blocks. The uploading functionality is already working, but I am facing an issue with setting the image sou ...

Issues with the drop-down menu in the <s:select> element arise when attempting to set the

While utilizing a Map to populate the Struts2 tag <s:select >, I have noticed that when the form is submitted multiple times, a blank line is added at the end of the list. For example, if the Map contains 2 key-value pairs, it displays 3 records and ...

Adjusting font sizes in JavaScript causes the text to resize

Within my HTML pages, I am adjusting the font size using JavaScript code like this: "document.body.style.fontSize = 100/50/20" However, whenever the font size changes, the text content on the page moves up or down accordingly. This can be disorienting for ...

Issue with bouncing dropdown menu

I am in the process of enhancing a Wordpress website by implementing a jQuery menu with sub-menus. Below is the jQuery code snippet: $(document).ready(function(){ $('.menu > li').hover(function(){ var position = $(this).position(); ...

Select the date that is three months from now using the datetimepicker feature of Bootstrap

I have two datetimepicker fields for selecting a start date and end date. I am utilizing the eonasdan datetimepicker plugin for Bootstrap. I am trying to set the range from the current date up to 3 months ahead. However, when I use maxdate:'+90d&apo ...

What is the proper way to add my image to CSS?

I'm encountering an issue while trying to insert my picture - I keep receiving a 404 error even though I believe my path is correct. Here are my files: main-menu phone.png _menu.scss Within my _menu.scss file, the following code is p ...

Manipulating images separately using the canvas

Currently, I am utilizing an HTML5 canvas to generate a collection of trees alongside their corresponding shadows. My objective is to ensure that each shadow corresponds with the position of a designated light source. While I have successfully drawn each t ...

Reveal and conceal information with a customized web address

I have a PHP and MySQL blog that I want to display in a div using show and hide JavaScript functions. Everything works fine with other divs, but the issue arises when clicking on a vanity URL causing my webpage to refresh every time it's clicked. The ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

When scrolling, a new page loads seamlessly

Recently, I came across a website that has an interesting feature where new content is loaded automatically while scrolling, seamlessly appending to the existing page. What's more fascinating is that not only does the content change, but the URL also ...

Simple method for displaying or hiding divs depending on the status of a selected radio button using CSS only

I am currently working on showing or hiding div elements based on the status of a radio button. These divs are located after the input buttons in a different section of the page, and I am facing challenges in referencing them accurately. This code is for ...

Compact selection box, vast information

My dilemma is having restricted space for a dropdown containing a considerable amount of text. Is it feasible to keep the dropdown width small while expanding the list popup size? Update: My browser of choice is Internet Explorer. ...