How to style checkbox using CSS?

    |
  • Added:
  • |
  • In: Wordpress

I am trying to style checkbox using the following:

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

But, it is still displaying the default checkbox. How to do it?

This Question Has 22 Answeres | Orginal Question | svirk

You can avoid adding extra markup. This works everywhere except IE for Desktop (but works in IE for Windows Phone and Microsoft Edge) via setting 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" />

You can use iCheck it is customized checkboxes and radio buttons for jQuery & Zepto, maybe it will help you

Make sure jQuery v1.7+ is loaded before the icheck.js

  1. Choose a color scheme, there are 10 different styles available:
    • Black — minimal.css
    • Red — red.css
    • Green — green.css
    • Blue — blue.css
    • Aero — aero.css
    • Grey — grey.css
    • Orange — orange.css
    • Yellow — yellow.css
    • Pink — pink.css
    • Purple — purple.css
  2. Copy /skins/minimal/ folder and icheck.js file to your site.
  3. Insert before in your HTML (replace your-path and color-scheme):

Example for a Red color scheme:

<link href="your-path/minimal/red.css" rel="stylesheet"> <script src="your-path/icheck.js"></script> 
  1. Add some checkboxes and radio buttons to your HTML:

  2. Add JavaScript to your HTML to launch iCheck plugin:

    <script> $(document).ready(function(){ $('input').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal', increaseArea: '20%' // optional }); }); </script> 
  3. For different from black color schemes use this code (example for Red):

    <script> $(document).ready(function(){ $('input').iCheck({ checkboxClass: 'icheckbox_minimal-red', radioClass: 'iradio_minimal-red', increaseArea: '20%' // optional }); }); </script> 
  4. Done

Here is a simple css solution no jQuery or javascript

I am using font awseome icons but you can use any image

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; } 

I prefer to use icon fonts (such as fontawesome) since it's easy to modify their colours with CSS and they scale really well on high pixel-density devices. So here's another pure CSS variant, using similar techniques to those above.

(Below is a static image so you can visualize the result; See the JSFiddle for an interactive version )

checkbox example

As with other solutions, it uses the LABEL element. An adjacent SPAN holds our checkbox character.

The HTML:

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

The CSS:

span.bigcheck-target { font-family: FontAwesome; /* use an icon font for the checkbox */ } input[type='checkbox'].bigcheck { position: relative; left: -999em; /* hide the real checkbox */ } input[type='checkbox'].bigcheck + span.bigcheck-target:after { content: "\f096"; /* In fontawesome, is an open square (fa-square-o) */ } input[type='checkbox'].bigcheck:checked + span.bigcheck-target:after { content: "\f046"; /* fontawesome checked box (fa-check-square-o) */ } /* ==== optional - colors and padding to make it look nice === */ body { background-color: #2C3E50; color: #D35400; font-family: sans-serif; font-weight: 500; font-size: 4em; /* set this to whatever size you want */ } span.bigcheck { display: block; padding: 0.5em;; } 

Here's the JSFiddle for it.

No JavaScript or Jquery required.

Change your checkbox style simple way.

HTML

<input type="checkbox" id="option"/> <label for="option"> <span></span> Click me </label> 

CSS

input[type="checkbox"]{ display: none; border: none !important; box-shadow: none !important; } input[type="checkbox"] + label span { background: url(http://imgh.us/uncheck.png); width: 49px; height: 49px; display: inline-block; vertical-align: middle; } input[type="checkbox"]:checked + label span { background: url(http://imgh.us/check_2.png); width: 49px; height: 49px; vertical-align: middle; } 

Here is JS Fiddle link : https://jsfiddle.net/05y2bge3/

This is quite an old post but recently I found a quite intresting solution to the problem.

You could use appearance: none; to turn off the checkbox his default style and then write your own over it like described here (Example 4).

Example fiddle

Unfortunately browser support is quite bad for the appearance option from my personal testing I only got Opera and chrome working correctly. But this whould be the way to go to keep it simple when better support comes or you only want to use chrome/ opera.

"Can I use?" link

quick-fix to add icon in front of text:

< asp:CheckBox... Text="< img src='/link/to/img.png' />My Text" /> 

Before you begin (as of Jan 2015)

The original question and answer are now ~5 years old. As such, this is a little bit of an update.

Firstly, there are a number of approaches when it comes to styling checkboxes. the basic tenet is:

  1. You will need to hide the default checkbox control which is styled by your browser, and cannot be overridden in any meaningful way using CSS.

  2. With the control hidden, you will still need to be able to detect and toggle its checked state

  3. The checked state of the checkbox will need to be reflected by styling a new element

The solution (in principle)

The above can be accomplished by a number of means- and you will often hear using CSS3 psuedo elements is the right way. Actually, there is no real right or wrong way, it depends on the approach most suitable for the context you will be using it in. That said, I have a preferred one.

  1. Wrap your checkbox in a label element. This will mean that even when it is hidden, you can still toggle its checked state on clicking anywhere within the label.

  2. Hide your checkbox

  3. Add a new element after the checkbox which you will style accordingly. It must appear after the checkbox so it can be selected using CSS and styled dependant on the :checked state. CSS cannot select 'backwards'.

The solution (in code)

label input { visibility: hidden;/* <-- hide the default checkbox, the rest is to hide and alllow 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>

Refinement (using icons)

But hey! I hear you shout. What about if I want to show a nice little tick or cross in the box? And I dont want to use background images!

Well, this is where CSS3's psuedo elements can come into play. These support the content property which allows you to inject unicode icons representing either state. Alternatively, you could use a third party font icon source such as font awesome (though make sure you also set the relevant font-family, e.g. to FontAwesome)

label input { display: none;/* <-- hide the default checkbox */ } label span {/* <-- style the artificial checkbox */ height: 10px; width: 10px; border: 1px solid grey; display: inline-block; position: relative; } [type=checkbox]:checked + span:before {/* <-- style its checked state..with a ticked icon */ content: '\2714'; position: absolute; top: -5px; left: 0; }
<label> <input type='checkbox'> <span></span> Checkbox label text </label>

UPDATE: The below answer references the state of things before widespread availability of CSS3. In modern browsers (including Internet Explorer 9 and later) it is more straightforward to create checkbox replacements with your preferred styling, without using javascript.

Here are some useful links:

It is worth noting that the fundamental issue has not changed. You still can't apply styles (borders, etc.) directly to the checkbox element and have those styles affect the display of the HTML checkbox. What has changed, however, is that it's now possible to hide the actual checkbox and replace it with a styled element of your own, using nothing but CSS. In particular, because CSS now has a widely supported :checked selector, you can make your replacement correctly reflect the checked status of the box.


OLDER ANSWER

Here's a useful article about styling checkboxes. Basically what that writer found was that it varies tremendously from browser to browser, and that many browsers always display the default checkbox no matter how you style it. So there really isn't an easy way.

It's not hard to imagine a workaround where you would use javascript to overlay an image on the checkbox and have clicks on that image cause the real checkbox to be checked. Users without javascript would see the default checkbox.

Edited to add: here's a nice script that does this for you; it hides the real checkbox element, replaces it with a styled span, and redirects the click events.

Simple to Implement and easily customizable solution

After a lot of Search and testing i got this solution which is simple to Implement and easier to customize ; in this Solution :

  1. You don't need external libraries and files
  2. You don't need to add extra html in your page
  3. You don't need to change checkbox names and id

simple put the flowing css at the top of your page and all checkboxes style will change like this : enter image description here

<style> 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 { 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 { content: "\2714"; padding:-5px; font-weight:bold; } </style> 

Here is a CSS/HTML only version, no Jquery or Javascript needed at all, Simple and clean html and really simple and short css.

here is the JSFiddle

http://jsfiddle.net/v71kn3pr/

Here is the HTML

<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 CSS

#myContainer { outline: black dashed 1px; width: 200px; } #myContainer input[type="checkbox"][name="myCheckbox"] { display: none; } #myContainer input[type="checkbox"][name="myCheckbox"]:not(:checked) + label.box { display: inline-block; width: 25px; height: 25px; border: black solid 1px; background: #FFF ; margin: 5px 5px; } #myContainer input[type="checkbox"][name="myCheckbox"]:checked + label.box { display: inline-block; width: 25px; height: 25px; border: black solid 1px; background: #F00; margin: 5px 5px; } #myContainer input[type="checkbox"][name="myCheckbox"] + label + label.text { font: normal 12px arial; display: inline-block; line-height: 27px; vertical-align: top; margin: 5px 0px; } 

This can be adapted to be able to have individual radio or checkboxes, grooups of checkboxes and groups of radio buttons as well.

This html/css, will allow you to also capture click on the label, so the checkbox will be checked and unchecked even if you click just on the label.

This type of checkbox/radio button works perfectly with any form, no problem at all. Have been tested using php, aspx, javafaces and coldfusion too.

No, you still can't style the checkbox itself, but I (finally) figured out how to style an illusion while keeping the functionality of clicking a checkbox. It means that you can toggle it even if the cursor isn't perfectly still without risking selecting text or triggering drag-and-drop!

This solution probably also fits radio buttons.

The following works in IE9, FF30.0 and Chrome 40.0.2214.91 and is just a basic example. You can still use it in combination with background images and pseudo-elements.

http://jsfiddle.net/o0xo13yL/1/

label { display: inline-block; position: relative; /* needed for checkbox absolute positioning */ background-color: #eee; padding: .5rem; border: 1px solid #000; border-radius: .375rem; font-family: "Courier New"; font-size: 1rem; line-height: 1rem; } label > input[type="checkbox"] { display: block; position: absolute; /* remove it from the flow */ width: 100%; height: 100%; margin: -.5rem; /* negative the padding of label to cover the "button" */ cursor: pointer; opacity: 0; /* make it transparent */ z-index: 666; /* place it on top of everything else */ } label > input[type="checkbox"] + span { display: inline-block; width: 1rem; height: 1rem; border: 1px solid #000; margin-right: .5rem; } label > input[type="checkbox"]:checked + span { background-color: #666; } <label> <input type="checkbox" /> <span>&nbsp;</span>Label text </label> 

I think the easiest way to do it is by styling a label and making the check-box invisible.

HTML

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

CSS

checkbox{ display:none; } checkbox + label{ /*Style for checkbox normal*/ width:16px; height:16px; } checkbox::checked + label, label.checked{ /*Style for checkbox checked*/ } 

the checkbox even though it is hidden will still be accessible and it's value will be sent when a form is submitted. For old browsers you might have to change the class of the label to checked using JavaScript because I don't think old versions of IE understand ::checked on the checkbox

You can achieve quite a cool custom checkbox effect by using the new abilities that come with the :after and :before pseudo classes. The advantage to this, is: You don't need to add anything more to the dom, just the standard checkbox.

Note this will only work for compatible browsers, I believe this is related to the fact that some browsers do not allow you to set :after and :before on input elements. Which unfortunately means for the moment only webkit browsers are supported. FF + IE will still allow the check-boxes to function, just un-styled, and this will hopefully change in the future (the code does not use vendor prefixes).

This is a Webkit browser solution only (Chrome, Safari, Mobile browsers)

See Example Fiddle

.myinput[type="checkbox"]:before{ position: relative; display: block; width: 11px; height: 11px; border: 1px solid #808080; content: ""; background: #FFF; } .myinput[type="checkbox"]:after{ position: relative; display: block; left: 2px; top: -11px; width: 7px; height: 7px; border-width: 1px; border-style: solid; border-color: #B3B3B3 #dcddde #dcddde #B3B3B3; content: ""; background-image: linear-gradient(135deg, #B1B6BE 0%,#FFF 100%); background-repeat: no-repeat; background-position:center; } .myinput[type="checkbox"]:checked:after{ background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%,#FFF 100%); } .myinput[type="checkbox"]:disabled:after{ -webkit-filter: opacity(0.4); } .myinput[type="checkbox"]:not(:disabled):checked:hover:after{ background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAQAAABuW59YAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAB2SURBVHjaAGkAlv8A3QDyAP0A/QD+Dam3W+kCAAD8APYAAgTVZaZCGwwA5wr0AvcA+Dh+7UX/x24AqK3Wg/8nt6w4/5q71wAAVP9g/7rTXf9n/+9N+AAAtpJa/zf/S//DhP8H/wAA4gzWj2P4lsf0JP0A/wADAHB0Ngka6UmKAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%,#FFF 100%); } .myinput[type="checkbox"]:not(:disabled):hover:after{ background-image: linear-gradient(135deg, #8BB0C2 0%,#FFF 100%); border-color: #85A9BB #92C2DA #92C2DA #85A9BB; } .myinput[type="checkbox"]:not(:disabled):hover:before{ border-color: #3D7591; } .myinput.large{ height:22px; width:22px; } .myinput.large[type="checkbox"]:before{ width: 20px; height: 20px; } .myinput.large[type="checkbox"]:after{ top: -20px; width: 16px; height: 16px; } .myinput.large.custom[type="checkbox"]:checked:after{ background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #B1B6BE 0%,#FFF 100%); } .myinput.large.custom[type="checkbox"]:not(:disabled):checked:hover:after{ background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGHRFWHRBdXRob3IAbWluZWNyYWZ0aW5mby5jb23fZidLAAAAk0lEQVQ4y2P4//8/AyUYwcAD+OzN/oMwshjRBoA0Gr8+DcbIhhBlAEyz+qZZ/7WPryHNAGTNMOxpJvo/w0/uP0kGgGwGaZbrKgfTGnLc/0nyAgiDbEY2BCRGdCDCnA2yGeYVog0Aae5MV4c7Gzk6CRqAbDM2w/EaQEgzXgPQnU2SAcTYjNMAYm3GaQCxNuM0gFwMAPUKd8XyBVDcAAAAAElFTkSuQmCC'), linear-gradient(135deg, #8BB0C2 0%,#FFF 100%); } 

Bonus Webkit style flipswitch fiddle

.flipswitch { position: relative; background: white; width: 120px; height: 40px; -webkit-appearance: initial; border-radius: 3px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); outline:none; font-size: 14px; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; cursor:pointer; border:1px solid #ddd; } .flipswitch:after { position:absolute; top:5%; display:block; line-height:32px; width:45%; height:90%; background:#fff; box-sizing:border-box; text-align:center; transition: all 0.3s ease-in 0s; color:black; border:#888 1px solid; border-radius:3px; } .flipswitch:after { left:2%; content: "OFF"; } .flipswitch:checked:after { left:53%; content: "ON"; } 

You can style checkboxs with a little trickery using the label element an example is below:


The CSS


.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; } 

The HTML


<div class="checkbox"> <input id="checkbox1" type="checkbox" value="1" /> <label for="checkbox1"></label> </div> 

And a FIDDLE for the above code. Note that some CSS doesn't work in older versions of browsers, but I'm sure there are some fancy JavaScript examples out there!

input[type=checkbox].css-checkbox { position: absolute; overflow: hidden; clip: rect(0 0 0 0); height:1px; width:1px; margin:-1px; padding:0; border:0; } input[type=checkbox].css-checkbox + label.css-label { padding-left:20px; height:15px; display:inline-block; line-height:15px; background-repeat:no-repeat; background-position: 0 0; font-size:15px; vertical-align:middle; cursor:pointer; } input[type=checkbox].css-checkbox:checked + label.css-label { background-position: 0 -15px; } .css-label{ background-image:url(http://csscheckbox.com/checkboxes/dark-check-green.png); } 

Yikes! All these workarounds have led me to the conclusion that the HTML checkbox kinda sucks if you want to style it.

As a forewarning, this isn't a css implementation. I just thought I'd share the workaround I came up with in case anyone else might find it useful.


I used the HTML5 canvas element.

The upside to this is that you don't have to use external images and can probably save some bandwidth.

The downside is that if a browser for some reason can't render it correctly, then there's no fallback. Though whether this remains an issue in 2017 is debatable.

Update

I found the old code quite ugly, so I decided to give it a rewrite.

Object.prototype.create = function(args){ var retobj = Object.create(this); retobj.constructor(args || null); return retobj; } 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; } }); 

Here's a working demo.

The new version uses prototypes and differential inheritance to create an efficient system for creating checkboxes. To create a checkbox:

var my_checkbox = Checkbox.create(); 

This will immediately add the checkbox to the DOM and hook up the events. To query whether a checkbox is checked:

my_checkbox.is_checked(); // true if checked, else false 

Also important to note is that I got rid of the loop.

Update 2

Something I neglected to mention in the last update is that using the canvas has more advantages than just making a checkbox that looks however you want it to look. You could also create multi-state checkboxes, if you wanted to.

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(prop in newobj) oldobj[prop] = newobj[prop]; 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; 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); }, is_checked: function(){ return this.state == 1; } }); 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 modified slightly the Checkbox used in the last snippet so that it is more generic, making it possible to "extend" it with a checkbox that has 3 states. Here's a demo. As you can see, it already has more functionality than the built-in checkbox.

Something to consider when you're choosing between JavaScript and CSS.

Old, poorly-designed code

Working Demo

First, set up 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, devise a way to have the canvas update itself.

(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 })(); 

The last part is to make it interactive. Luckily, it's pretty simple:

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

This is where you might have problems in IE, due to their weird event handling model in javascript.


I hope this helps someone, it definitely suited my needs.

There is a way to do this using just css. We can (ab)use the label element and style that instead. The caveat is that this will not work for IE8 and lower versions.

CSS:

.myCheckbox input { // display: none; // Better than display: none for accessibility reasons 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"); } 

HTML:

<label for="test">Label for my styled "checkbox"</label> <label class="myCheckbox"> <input type="checkbox" name="test"/> <span></span> </label> 

Warning: the following was true at the time of writing, but in the meantime things have progressed.

AFAIK modern browsers display checkboxes using the native OS control, so there's no way to style them.

Modify checkbox style with plain css3, don't required any js&html manipulation.

.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>

This is simplest way and you can choose which checkeboxes to give this style.

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>Check box Text</span> </label> 

I'd follow the advice of SW4's answer - to hide the checkbox and to cover it with custom span, suggesting this HTML

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

The wrap in label neatly allows clicking the text without the need of "for-id" attribute linking. However,

do not hide it using visibility: hidden or display: none

It works with clicking or tapping, but that is a lame way to use checkboxes. Some people still use much more effective tab to move focus, space to activate, and hiding with that method disables it. If the form is long, one will save someone's wrists to use tabindex or accesskey attributes. And if you observe the system checkbox behavior, there is a decent shadow on hover. Well styled checkbox should follow this behavior.

cobberboy's answer recommends Font Awesome which is usually better than bitmap since fonts are scallable vectors. Working with the HTML above, I'd suggest these CSS rules:

1: hide checkboxes

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

I use just negative z-index since my example uses big enough checkbox skin to cover it fully. I don't recommend left: -999px since it is not reusable in every layout. Bushan wagh's answer provides bulletproof way to hide it and convince the browser to use tabindex, so it is a good alternative. Anyway, both is just a hack. Proper way today is appearance: none, see 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; } 

\00f096 is Font Awesome's square-o, padding is adjusted to provide even dotted outline on focus (see below)

4: add checkbox checked skin

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

\00f046 is Font Awesome's check-square-o, which is not the same width as square-o, which is the reason for the width style above

5: add focus outline

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

Safari doesn't provide this feature (see @Jason Sankey's comment), you shoud use window.navigator to detect the browser and skip it if it is Safari.

6: set gray color for disabled checkbox

input[type="checkbox"]:disabled+span { color: #999; } 

7: set hover shadow on non-disabled checkbox

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

demo Fiddle

Try to hover the mouse over the checkboxes and use tab and shift+tab to move and space to toggle.


Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

Connect Social With PHPAns
Top