How to create an on/off switch with Javascript/CSS? - javascript

I want to have a sliding switch. On the left would be Off and on the right would be On. When the user toggles the switch, I want the 'slider' portion to slide to the other side and indicate it is off. I could then have a callback that takes as input the state of the toggle switch so I can act accordingly.
Any idea how to do this?

check out this generator: On/Off FlipSwitch
you can get various different style outcomes and its css only - no javascript!

You mean something like IPhone checkboxes?
Try Thomas Reynolds' iOS Checkboxes script:
Once the files are available to your site, activating the script is very easy:
...
$(document).ready(function() {
$(':checkbox').iphoneStyle();
});
Results:

Using plain javascript
<html>
<head>
<!-- define on/off styles -->
<style type="text/css">
.on { background:blue; }
.off { background:red; }
</style>
<!-- define the toggle function -->
<script language="javascript">
function toggleState(item){
if(item.className == "on") {
item.className="off";
} else {
item.className="on";
}
}
</script>
</head>
<body>
<!-- call 'toggleState' whenever clicked -->
<input type="button" id="btn" value="button"
class="off" onclick="toggleState(this)" />
</body>
</html>
Using jQuery
If you use jQuery, you can do it using the toggle function, or using the toggleClass function inside click event handler, like this:
$(document).ready(function(){
$('a#myButton').click(function(){
$(this).toggleClass("btnClicked");
});
});
Using jQuery UI effects, you can animate transitions: http://jqueryui.com/demos/toggleClass/

Initial answer from 2013
If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.
It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.
Source code is available on Github.
Note from 2018
I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.
Please consider having a look at modern Switches like those.

You can achieve this using HTML and CSS and convert a checkbox into a HTML Switch.
input.cmn-toggle-round + label {
padding: 2px;
width: 100px;
height: 30px;
background-color: #dddddd;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
}
input.cmn-toggle-round + label:before, input.cmn-toggle-round + label:after {
display: block;
position: absolute;
top: 1px;
left: 1px;
bottom: 1px;
content: "";
}
input.cmn-toggle-round + label:before {
right: 1px;
background-color: #f1f1f1;
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
-ms-border-radius: 30px;
-o-border-radius: 30px;
border-radius: 30px;
-webkit-transition: background 0.4s;
-moz-transition: background 0.4s;
-o-transition: background 0.4s;
transition: background 0.4s;
}
input.cmn-toggle-round + label:after {
width: 40px;
background-color: #fff;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
-ms-border-radius: 100%;
-o-border-radius: 100%;
border-radius: 100%;
-webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
-webkit-transition: margin 0.4s;
-moz-transition: margin 0.4s;
-o-transition: margin 0.4s;
transition: margin 0.4s;
}
input.cmn-toggle-round:checked + label:before {
background-color: #8ce196;
}
input.cmn-toggle-round:checked + label:after {
margin-left: 60px;
}
.cmn-toggle {
position: absolute;
margin-left: -9999px;
visibility: hidden;
}
.cmn-toggle + label {
display: block;
position: relative;
cursor: pointer;
outline: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<div class="switch">
<input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round" type="checkbox">
<label for="cmn-toggle-1"></label>
</div>

Outline: Create two elements: a slider/switch and a trough as a parent of the slider. To toggle the state, switch the slider element between an "on" and an "off" class. In the style for one class, set "left" to 0 and leave "right" the default; for the other class, do the opposite:
<style type="text/css">
.toggleSwitch {
width: ...;
height: ...;
/* add other styling as appropriate to position element */
position: relative;
}
.slider {
background-image: url(...);
position: absolute;
width: ...;
height: ...;
}
.slider.on {
right: 0;
}
.slider.off {
left: 0;
}
</style>
<script type="text/javascript">
function replaceClass(elt, oldClass, newClass) {
var oldRE = RegExp('\\b'+oldClass+'\\b');
elt.className = elt.className.replace(oldRE, newClass);
}
function toggle(elt, on, off) {
var onRE = RegExp('\\b'+on+'\\b');
if (onRE.test(elt.className)) {
elt.className = elt.className.replace(onRE, off);
} else {
replaceClass(elt, off, on);
}
}
</script>
...
<div class="toggleSwitch" onclick="toggle(this.firstChild, 'on', 'off');"><div class="slider off" /></div>
Alternatively, just set the background image for the "on" and "off" states, which is a much easier approach than mucking about with positioning.

You can take a look at Shield UI's Switch widget. It is as easy to use as this:
<input id="switch3" type="checkbox" value="" />
<script>
jQuery(function ($) {
$("#switch3").shieldSwitch({
onText: "Yes, save it",
ffText: "No, delete it",
cls: "large"
});
});
</script>

Related

How can I add interactive semantics to a pseudo element with CSS or JavaScript?

I have a small carousel that plays automatically on page load, using HTML, CSS and JavaScript and definitely no jQuery.
To add a pause/play option there is a span with role="checkbox" followed by a label.
The label itself is hidden and has no content. The span has two pseudo elements. On first showing, the pseudo element shows the ⏸ character, controlled by a CSS ::after class. When clicked, the span has the class "is-clicked" added, at which point the ▶ character is displayed, controlled by another ::after class
It is focusable and can be activated with the keyboard by hitting the Enter key, but when I check with Lighthouse, I keep getting the "Focusable elements should have interactive semantics".
Why is this?
Here is the code:
/* detect keyboard users */
function handleFirstTab(e) {
if (e.key === 'Tab') { // the 'I am a keyboard user' key
document.body.classList.add('user-is-tabbing');
window.removeEventListener('keydown', handleFirstTab);
}
}
let checkboxEl = document.getElementById('checkbox');
let labelEl = document.getElementById('checkboxLabel');
labelEl.onclick = function handleLabelClick() {
checkboxEl.focus();
toggleCheckbox();
}
function toggleCheckbox() {
let isChecked = checkboxEl.classList.contains('is-checked');
checkboxEl.classList.toggle('is-checked', !isChecked);
checkboxEl.setAttribute('aria-checked', !isChecked);
}
checkboxEl.onclick = function handleClick() {
toggleCheckbox();
}
checkboxEl.onkeypress = function handleKeyPress(event) {
let isEnterOrSpace = event.keyCode === 32 || event.keyCode === 13;
if(isEnterOrSpace) {
toggleCheckbox();
}
}
.link {
height: auto;
border: 1px solid #000;
margin-bottom: 1rem;
width: 80%;
display: block;
}
#carousel-checkbox {
margin-bottom: 1rem;
height: 50px;
width: 100px;
display: inline-block;
}
#carousel-checkbox input {
display: none;
}
#carousel-checkbox label {
display: inline-block;
vertical-align: middle;
}
#carousel-checkbox #checkbox {
position: relative;
top: 0;
left: 30px;
padding: 0.5rem 1rem;
background: rgba(255,255,255, 0.5);
}
#carousel-checkbox #checkbox:hover {
cursor: pointer;
}
#carousel-checkbox #checkbox:focus {
border: 1px dotted var(--medium-grey);
}
#carousel-checkbox #checkbox::after {
content: "⏸";
font-size: 1.5rem;
color: var(--theme-dark);
}
#carousel-checkbox #checkbox.is-checked::after {
content: "▶";
}
<div class="link">A bit of text with a dummy link to demonstrate the keyboard tabbing navigation. </div>
<div id="carousel-checkbox"><span id="checkbox" tabindex="0" role="checkbox" aria-checked="false" aria-labelledby="checkboxLabel"></span><label id="checkboxLabel"></label></div>
<div class="link">Another link to another dummy link</div>
Why is this? Is it because the pseudo elements don't have a name attribute or something like that?
I have tried a different way, by dropping the pseudo elements and trying to change the span innerHTML depending on whether the class 'is-clicked' exists or not, but although I can get the pause character to display initially, it won't change the innerHTML to the play character when the span is clicked again.
Short Answer
This is a warning rather than an error, it is telling you to check that the item actually is interactive.
Now you have got the interactivity on the element so you can ignore that issue.
Long answer
Why not just use a <input type="checkbox"> and save yourself an awful lot of extra work?
You can hide a checkbox with a visually hidden class.
This then allows you to do the same trick with a pseudo element as the visual representation of the state.
I have made several changes to your example that mean you don't have to worry about capturing keypresses etc. and can just use a click handler so your JS is far simpler.
Notice the trick with the label where I add some visually hidden text within it so the label is still visible (so we can still use psuedo elements!).
I then use #checkbox1 ~ label to access the label with CSS so we can change the state.
The final thing to notice is how I changed the content property slightly. This is because some screen readers will try and read out pseudo elements so I added alt text that was blank. Support isn't great at just over 70%, but it is worth adding for browsers that do support it.
Example
The below hopefully illustrates a way of achieving what you want with a checkbox.
There may be a few errors as I just adapted your code so please do not just copy and paste!
note: a checkbox should not work with Enter, only with Space. If you want it to work with both it should instead be a toggle switch etc. so that would be a completely different pattern.
let checkboxEl = document.getElementById('checkbox1');
let labelEl = document.querySelector('#checkboxLabel');
function toggleCheckbox() {
let isChecked = checkboxEl.classList.contains('is-checked');
checkboxEl.classList.toggle('is-checked', !isChecked);
checkboxEl.setAttribute('aria-checked', !isChecked);
}
checkboxEl.onclick = function handleClick() {
toggleCheckbox();
}
.link {
height: auto;
border: 1px solid #000;
margin-bottom: 1rem;
width: 80%;
display: block;
}
#carousel-checkbox {
margin-bottom: 1rem;
height: 50px;
width: 100px;
display: inline-block;
}
.visually-hidden {
border: 0;
padding: 0;
margin: 0;
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
clip: rect(1px, 1px, 1px, 1px); /*maybe deprecated but we need to support legacy browsers */
clip-path: inset(50%); /*modern browsers, clip-path works inwards from each corner*/
white-space: nowrap; /* added line to stop words getting smushed together (as they go onto seperate lines and some screen readers do not understand line feeds as a space */
}
#carousel-checkbox label {
display: inline-block;
vertical-align: middle;
}
#carousel-checkbox #checkbox1 {
position: relative;
top: 0;
left: 30px;
padding: 0.5rem 1rem;
background: rgba(255,255,255, 0.5);
}
#carousel-checkbox #checkbox1 ~label:hover {
cursor: pointer;
}
#carousel-checkbox #checkbox1:focus ~ label {
border: 1px dotted #333;
}
#carousel-checkbox #checkbox1 ~label::after {
content: "⏸" / "";
font-size: 1.5rem;
color: #000;
}
#carousel-checkbox #checkbox1.is-checked ~label::after {
content: "▶" / "";
}
<div class="link">A bit of text with a dummy link to demonstrate the keyboard tabbing navigation. </div>
<div id="carousel-checkbox">
<input type="checkbox" id="checkbox1" class="visually-hidden">
<label for="checkbox1" id="checkboxLabel">
<span class="visually-hidden">Pause animations</span>
</label>
</div>
<div class="link">Another link to another dummy link</div>
In the end, I gave up on using a checkbox, due to the difficulties with iPad/iOS not responding to checkbox events. Whilst it worked in codepen on iOS it wouldn't work on the actual site. So I switched to a button.
Here is the code, which is fully accessible with no 'interactive semantics' warnings, shown with some dummy slides. The animation is based on having only three slides. If you wanted more or less, then the timings would have to be adjusted accordingly. All I need now is to style the pause button.
let element = document.getElementById("pause");
function toggleButton() {
element.classList.toggle("paused");
if (element.innerHTML === "⏸") {
element.innerHTML = "▶";
}
else {
element.innerHTML = "⏸";
}
}
element.onclick = function handleClick() {
toggleButton();
}
#carousel {
height: auto;
max-width: 1040px;
position: relative;
margin: 4rem auto 0;
}
#carousel > * {
animation: 12s autoplay6 infinite linear;
position: absolute;
top: 0;
left: 0;
opacity: 0.0;
}
#carousel .one {
position: relative;
}
.homeSlides {
height: 150px;
width: 400px;
background-color: #ff0000;
}
.homeSlides.two {
background-color: #0fff00;
}
.homeSlides.three {
background-color: #e7e7e7;
}
#keyframes autoplay6 {
0% {opacity: 0.0}
4% {opacity: 1.0}
33.33% {opacity: 1.0}
37.33% {opacity: 0.0}
100% {opacity: 0.0}
}
#carousel > *:nth-child(1) {
animation-delay: 0s;
}
#carousel > *:nth-child(2) {
animation-delay: 4s;
}
#carousel > *:nth-child(3) {
animation-delay: 8s;
}
#carousel-button {
position: relative;
height: 100%;
width: auto;
}
#carousel-button button {
position: absolute;
top: -3.5rem;
right: 5rem;
padding: 0 0.5rem 0.25rem;;
background: #fff;
z-index: 98;
font-size: 2rem;
cursor: pointer;
}
body.user-is-tabbing #carousel-button button:focus {
outline: 1px dotted #333;
}
body:not(.user-is-tabbing) #carousel-button button:focus {
outline: none;
}
#carousel-button button:hover {
cursor: pointer;
}
#carousel-button ~ #carousel * {
animation-play-state: running;
}
#carousel-button button.paused ~ #carousel * {
animation-play-state: paused;
}
<div id="carousel-button"><button id="pause" class="">⏸</button>
<div id="carousel">
<div class="homeSlides one">This is div one</div>
<div class="homeSlides two">This is div two</div>
<div class="homeSlides three">This is div three</div>
</div>
</div>

how to hide the "box" of a check box and only keep the word lable [duplicate]

I am trying to style a checkbox using the following:
<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />
But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?
UPDATE:
The below answer references the state of things before widespread availability of CSS 3. 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:
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
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, that writer found 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.
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. Firefox + Internet Explorer will still allow the checkboxes to function, just unstyled, 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
$(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;
}
.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;
}
/* Large checkboxes */
.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;
}
/* Custom checkbox */
.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%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>Normal:</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" checked="checked" /></td>
<td><input type="checkbox" disabled="disabled" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" /></td>
</tr>
<tr>
<td>Small:</td>
<td><input type="checkbox" class="myinput" /></td>
<td><input type="checkbox" checked="checked" class="myinput" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput" /></td>
</tr>
<tr>
<td>Large:</td>
<td><input type="checkbox" class="myinput large" /></td>
<td><input type="checkbox" checked="checked" class="myinput large" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput large" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large" /></td>
</tr>
<tr>
<td>Custom icon:</td>
<td><input type="checkbox" class="myinput large custom" /></td>
<td><input type="checkbox" checked="checked" class="myinput large custom" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput large custom" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large custom" /></td>
</tr>
</table>
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;
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";
}
<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" />
<span></span>
<br>
<input type="checkbox" checked="checked" class="flipswitch" />
<span></span>
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:
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.
With the control hidden, you will still need to be able to detect and toggle its checked state.
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 that using CSS3 pseudo-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.
Wrap your checkbox in a label element. This will mean that even when it is hidden, you can still toggle its checked state by clicking anywhere within the label.
Hide your checkbox.
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 dependent 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 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>
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 don't want to use background images!
Well, this is where CSS3's pseudo-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 */
}
/* 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>
There is a way to do this using just CSS. We can (ab)use the label element and style that element instead. The caveat is that this will not work for Internet Explorer 8 and lower 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>
I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
CODEPEN
Steps
Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
Add :focus style to make the checkbox accessible.
Done
Here is how I did it.
.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>
Much more stylish 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>
Modern accessible solution - use accent-color
Use the new accent-color property and make certain to meet a proper contrast ratio of 3:1 to ensure accessibility. This also works for radio buttons.
.red-input {
accent-color: #9d3039;
height: 20px; /* not needed */
width: 20px; /* not needed */
}
<input class="red-input" type="checkbox" />
<!-- Radio button example -->
<input class="red-input" type="radio" />
Old answer, I only recommend this if you need more customization than the above offers:
I have been scrolling and scrolling and tons of these answers simply throw accessibility out the door and violate WCAG in more than one way. I threw in radio buttons since most of the time when you're using custom checkboxes you want custom radio buttons too.
Fiddles:
Checkboxes - pure CSS - free from 3rd party libraries
Radio buttons - pure CSS - free from 3rd party libraries
Checkboxes* that use FontAwesome but could be swapped with Glyphicons, etc. easily
Late to the party but somehow this is still difficult in 2019, 2020, 2021 so I have added my three solutions which are accessible and easy to drop in.
These are all JavaScript free, accessible, and external library free*...
If you want to plug-n-play with any of these just copy the style sheet from the fiddles, edit the color codes in the CSS to fit your needs, and be on your way. You can add a custom svg checkmark icon if you want for the checkboxes. I've added lots of comments for those non-CSS'y folks.
If you have long text or a small container and are encountering text wrapping underneath the checkbox or radio button input then just convert to divs like this.
Longer explanation:
I needed a solution that does not violate WCAG, doesn't rely on JavaScript or external libraries, and that does not break keyboard navigation like tabbing or spacebar to select, that allows focus events, a solution that allows for disabled checkboxes that are both checked and unchecked, and finally a solution where I can customize the look of the checkbox however I want with different background-color's, border-radius, svg backgrounds, etc.
I used some combination of this answer from #Jan Turoň to come up with my own solution which seems to work quite well. I've done a radio button fiddle that uses a lot of the same code from the checkboxes in order to make this work with radio buttons too.
I am still learning accessibility so if I missed something please drop a comment and I will try to correct it.
Here is a code example of my checkboxes:
input[type="checkbox"] {
position: absolute;
opacity: 0;
z-index: -1;
}
/* Text color for the label */
input[type="checkbox"]+span {
cursor: pointer;
font: 16px sans-serif;
color: black;
}
/* Checkbox un-checked 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;
}
/* Checked checkbox style (in this case the background is green #e7ffba, change this to change the color) */
input[type="checkbox"]:checked+span:before {
/* NOTE: Replace the url with a path to an SVG of a checkmark to get a checkmark icon */
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;
/* The size of the checkmark icon, you may/may not need this */
background-size: 25px;
border-radius: 2px;
background-color: #e7ffba;
color: white;
}
/* Adding a dotted border around the active tabbed-into checkbox */
input[type="checkbox"]:focus+span:before,
input[type="checkbox"]:not(:disabled)+span:hover:before {
/* Visible in the full-color space */
box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1);
/* Visible in Windows high-contrast themes
box-shadow will be hidden in these modes and
transparency will not be hidden in high-contrast
thus box-shadow will not show but the outline will
providing accessibility */
outline-color: transparent; /*switch to transparent*/
outline-width: 2px;
outline-style: dotted;
}
/* Disabled checkbox styles */
input[type="checkbox"]:disabled+span {
cursor: default;
color: black;
opacity: 0.5;
}
/* Styles specific to this fiddle that you do not need */
body {
padding: 1em;
}
h1 {
font-size: 18px;
}
<h1>
NOTE: Replace the url for the background-image in CSS with a path to an SVG in your solution or CDN. This one was found from a quick google search for a checkmark icon cdn
</h1>
<p>You can easily change the background color, checkbox symbol, border-radius, etc.</p>
<label>
<input type="checkbox">
<span>Try using tab and space</span>
</label>
<br>
<label>
<input type="checkbox" checked disabled>
<span>Disabled Checked Checkbox</span>
</label>
<br>
<label>
<input type="checkbox" disabled>
<span>Disabled Checkbox</span>
</label>
<br>
<label>
<input type="checkbox">
<span>Normal Checkbox</span>
</label>
<br>
<label>
<input type="checkbox">
<span>Another Normal Checkbox</span>
</label>
I'd follow the advice of SW4's answer. Not anymore: Volomike's answer is far superior to all the answers here (note my suggested improvement in the comment to the answer). Proceed reading this answer if you are curious about alternative approaches, which this answer comments.
First of all, hide the checkbox and to cover it with a 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 by 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. The well styled checkbox should follow this behavior.
cobberboy's answer recommends Font Awesome which is usually better than bitmap since fonts are scalable vectors. Working with the HTML above, I'd suggest these CSS rules:
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 a bulletproof way to hide it and convince the browser to use tabindex, so it is a good alternative. Anyway, both is just a hack. The proper way today is appearance: none, see Joost's answer:
input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
}
Style checkbox label
input[type="checkbox"] + span {
font: 16pt sans-serif;
color: #000;
}
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).
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.
Add focus outline
input[type="checkbox"]:focus + span:before {
outline: 1px dotted #aaa;
}
Safari doesn't provide this feature (see #Jason Sankey's comment), see this answer for Safari-only CSS
Set gray color for disabled checkbox
input[type="checkbox"]:disabled + span {
color: #999;
}
Set hover shadow on non-disabled checkbox
input[type="checkbox"]:not(:disabled) + span:hover:before {
text-shadow: 0 1px 2px #77F;
}
Test it on JS Fiddle
Try to hover the mouse over the checkboxes and use Tab and Shift+Tab to move and Space to toggle.
With pure CSS, nothing fancy with :before and :after, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now 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 & Conditions</label>
</form>
The CSS Basic User Interface Module Level 4 adds support for this (finally) via a new solution called accent-color, and it's actually quite simple, unlike pretty much every other answer here:
input {
accent-color: rebeccapurple;
}
<input type="checkbox" />
Simply set whatever CSS color (e.g. named value, hex code, etc.) you want in as the value of accent-color, and it will be applied.
This currently works in Chrome (v93+), Edge (v93+), Firefox (v92+), Opera (v79+), and Safari (v15.4+).
Note: Edge, Chrome, and Opera (and possibly Safari; I can't test that) currently don't support alpha channel values via rgba() either (the RGB values of rgba() will still "work"; the alpha channel will simply be ignored by the browser). See MDN Browser Support for more information.
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:
You don't need external libraries and files
You don't need to add
extra HTML in your page
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:
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>
You can style checkboxes with a little trickery using the label element an example is 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>
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!
You can avoid adding extra markup. This works everywhere except IE 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" />
Recently I found a quite interesting solution to the problem.
You could use appearance: none; to turn off the checkbox's default style and then write your own over it like described 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 browser support is quite bad for the appearance option. From my personal testing I only got Opera and Chrome working correctly. But this would be the way to go to keep it simple when better support comes or you only want to use Chrome/Opera.
Example JSFiddle
"Can I use?" link
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.)
As with other solutions, it uses the label element. An adjacent span holds our checkbox character.
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;
}
<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>
Here's the JSFiddle for it.
My solution
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>
You can simply use appearance: none on modern browsers, so that there is no default styling and all your styles are applied properly:
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;
}
Here is a simple CSS solution without any jQuery or JavaScript code.
I am using FontAwseome 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;
}
From my googling, this is the easiest way for checkbox styling. Just add :after and :checked:after CSS based on your design.
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>
Modify the checkbox style with plain CSS. This does not require any JavaScript or 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>
Yikes! All these workarounds have led me to the conclusion that the HTML checkbox kind of 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.
SCSS / SASS Implementation
A more modern approach
For those using SCSS (or easily converted to SASS), the following will be helpful. Effectively, make an element next to the checkbox, which is the one that you will style. When the checkbox is clicked, the CSS restyles the sister element (to your new, checked style). Code is below:
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>
A simple and lightweight template as well:
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/
I think the easiest way to do it is by styling a label and making the checkbox invisible.
HTML
<input type="checkbox" id="first" />
<label for="first"> </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 its 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 Internet Explorer understand ::checked on the checkbox.
Here's a modern version with a little animation, and simple styling you can customize:
.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);
}
No JavaScript or jQuery required.
Change your checkbox style simple way.
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;
}
<input type="checkbox" id="option" />
<label for="option"> <span></span> Click me </label>
Here is a JSFiddle link
Custom checkbox with CSS (WebKit browser solution only Chrome, Safari, Mobile browsers)
<input type="checkbox" id="cardAccptance" name="cardAccptance" value="Yes">
<label for="cardAccptance" class="bold"> Save Card for Future Use</label>
CSS:
/* The checkbox-cu */
.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;
}
/* Hide the browser's default checkbox-cu */
.checkbox-cu input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox-cu */
.checkmark {
position: absolute;
top: 4px;
left: 0;
height: 20px;
width: 20px;
background-color: #eee;
border: 1px solid #999;
border-radius: 0;
box-shadow: none;
}
/* On mouse-over, add a grey background color */
.checkbox-cu:hover input~.checkmark {
background-color: #ccc;
}
/* When the checkbox-cu is checked, add a blue background */
.checkbox-cu input:checked~.checkmark {
background-color: transparent;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.checkbox-cu input:checked~.checkmark:after {
display: block;
}
/* Style 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;
}
By using Materialize with a custom stylesheet, you can achieve something like this:
CSS code
.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 code
<label>
<input type="checkbox" class="custom_checkbox" />
<span>Text</span>
</label>
Demo
JSFiddle demo
This helped me to change style (color) for checkbox
input[type=checkbox] {
accent-color: red;
}
We can also use the same for radio buttons.
This is simplest way and you can choose which checkboxes 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>
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, ASP.NET (.aspx), JavaServer Faces, and ColdFusion too.

Issue while using transitions + opacity change + overflow hidden

If you see the code sample I have shared, you can see the overlay going outside the box. I traced the issue down to the transition attribute.
I want to remove the content outside of the div. Overflow isn't working as it is supposed to. (removing transition works, but I would like to keep it if possible)
Any help is appreciated
Codepen Link
CODE
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
Actually it is the border-radius that is not getting respected when the transition is happening. This is because of creation of compositing layers for accelerated rendering and can be explained by having a look at the following articles:
HTML5 Rocks - Accelerated Rendering in Chrome
GPU Accelerated Compositing in Chrome.
Why does the issue not happen when transition is disabled?
When styles change but none of the criteria that necessitates the creation of a compositing layer is satisfied (that is, no animation or transition or 3D transform etc):
There is no compositing layer and so the whole area seems to get repainted at every change. Since a full repaint happens there is no issue.
View the below snippet (in full screen mode) after enabling "Show paint rects" and "Show composited layer borders" from Dev tools and observe the following:
No areas with an orange border (compositing layer) are created.
Every time the styles are modified by setting the focus on one of the a tags, the whole area gets repainted (a red or green blinking area).
.outer {
position: relative;
height: 100px;
width: 100px;
margin-top: 50px;
border: 1px solid red;
overflow: hidden;
}
.border-radius {
border-radius: 50px;
}
.inner {
width: 50px;
height: 50px;
background-color: gray;
opacity: 0.75;
}
a:focus + .outer.border-radius > .inner {
transform: translateX(50px);
height: 51px;
opacity: 0.5;
}
<a href='#'>Test</a>
<div class='outer border-radius'>
<div class='inner'>I am a strange root.
</div>
</div>
Why does adding a transition create a problem?
Initial rendering has no compositing layer because there is no transition yet on the element. View the below snippet and note how when the snippet is run a paint (red or green blinking area) happens but no compositing layer (area with orange border) is created.
When transition starts, Chrome splits them into different compositing layers when some properties like opacity, transform etc are being transitioned. Notice how two areas with orange borders are displayed as soon as the focus is set on one of the anchor tags. These are the compositing layers that got created.
The layer splitting is happening for accelerated rendering. As mentioned in the HTML5 Rocks article, the opacity and transform changes are applied by changing the attributes of the compositing layer and no repainting occurs.
At the end of the transition, a repaint happens to merge all the layers back into a single layer because compositing layers are no longer applicable (based on criteria for creation of layers).
.outer {
position: relative;
height: 100px;
width: 100px;
margin-top: 50px;
border: 1px solid red;
overflow: hidden;
}
.border-radius {
border-radius: 50px;
}
.inner {
width: 50px;
height: 50px;
background-color: gray;
transition: all 1s 5s;
/*transition: height 1s 5s; /* uncomment this to see how other properties don't create a compositing layer */
opacity: 0.75;
}
a:focus + .outer.border-radius > .inner {
transform: translateX(50px);
opacity: 0.5;
/*height: 60px; */
}
<a href='#'>Test</a>
<div class='outer border-radius'>
<div class='inner'>I am a strange root.
</div>
</div>
This illustrates that when the layers are merged back and full repaint happens, the border-radius on the parent also gets applied and respected. However, during transition only the compositing layer's properties are changed, so the layer seems to become unaware of the properties of other layers and thus doesn't respect the border-radius of the parent.
I would assume this to be because of the way rendering of layers work. Each layer is a software bitmap and so it kind of becomes equivalent to having a circular image and then placing a div on top of it. That would obviously not result in any clipping of content.
The comment in this bug thread also seems to confirm that a repaint happens when a separate layer is no longer required.
We want to repaint if "gets own layer" is going to change
Note: Though they are Chrome specific, I think the behavior should be similar in others also.
What is the solution?
The solution seems to be to create a separate stacking context for the parent (.qs-timer) element. Creating a separate stacking context seems to result in a separate compositing layer being created for the parent and this solves the issue.
As mentioned by BoltClock in this answer, any one of the following options would create a separate stacking context for the parent and doing one of them seems to resolve the issue.
Setting a z-index on the parent .qs-timer to anything other than auto.
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
z-index: 1; /* creates a separate stacking context */
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
Setting opacity to anything less than 1. I have used 0.99 in the below snippet as it doesn't cause any visual difference.
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
opacity: 0.99; /* creates a separate stacking context */
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
Adding a transform to the element. I have used translateZ(0px) in the below snippet as this also doesn't create any visual difference.
var timer = setInterval(function() {
document.querySelector(".qs-timer-overlay").style.opacity = (document.querySelector(".qs-timer-overlay").style.opacity * 1) + 0.1;
if (document.querySelector(".qs-timer-overlay").style.opacity * 1 == 1) {
clearInterval(timer);
}
}, 1000);
.qs-main-header .qs-timer {
padding: 13px 10px;
min-width: 130px;
text-align: center;
display: inline-block;
background-color: #dd8b3a;
color: #FFF;
font-size: 20px;
border-radius: 50px;
text-transform: uppercase;
float: right;
cursor: pointer;
position: relative;
overflow: hidden;
transform: translateZ(0px) /* creates a separate stacking context */
}
.qs-main-header .qs-timer-overlay {
z-index: 1;
width: 10%;
max-width: 100%;
position: absolute;
height: 100%;
top: 0;
left: 0;
background-color: #c7543e;
opacity: 0.0;
/* border-radius: 50px 50px 0px 50px; */
}
.qs-main-header .qs-timer-content {
z-index: 2;
position: relative;
}
.scale-transition {
-webkit-transition: all 1s;
transition: all 1s;
}
<div class="qs-main-header">
<div class="qs-timer scale-transition ng-hide" ng-show="visibility.timer">
<div class="scale-transition qs-timer-overlay"></div>
<div class="qs-timer-content ng-binding">0 <span class="ng-binding">Sec(s)</span>
</div>
</div>
</div>
The first two approaches are more preferable than the third because the third one works only on a browser that supports CSS transforms.
Yes, adding opacity: 0.99; to .qs-timer issue will fixed.
When opacity: 1 OR NOT define:
In this special case, there is no transparency involved so that gfx could avoid doing the expensive things.
In case Opacity: 0.99:
nsIFrame::HasOpacity() decides that there is an opacity, so gfx include valuable things. ( likes opacity with border-radius)
For more help Special case opacity:0.99 to treat it as opacity:1 for graphics , This ticket is not providing the opinion of our actual goal, but giving the idea about what is happening inside of CSS.

animate fixed bottom bar to appear on hover

i have a bar that is fixed to the bottom of the browser. i want to make the bar displayed as 'none', so that when a user hovers over the bar it is displayed until they hover out.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
html {
background: #34495e;
}
#pagebottom {
width: 92%;
height: 20px;
background: rgba(255, 255, 255, 0.80);
margin-left: 4%;
margin-right: 4%;
bottom: 0;
position: fixed;
color: #3498db;
text-align: center;
}
</style>
</head>
<body>
<div id="pagebottom">
random text
</div>
</body>
</html>
try this css solution
#pagebottom {
width: 92%;
height: 20px;
background: rgba(255, 255, 255, 0.80);
margin-left: 4%;
margin-right: 4%;
bottom: 0;
position: fixed;
color: #3498db;
text-align: center;
opacity:0;
}
#pagebottom:hover{
opacity:1;
transition:all .5s linear;
}
You can accomplish this with CSS. No JavaScript needed.:
#pagebottom {
opacity: 0;
width: 92%;
height: 20px;
background: rgba(255, 255, 255, 0.80);
margin-left: 4%;
margin-right: 4%;
bottom: 0;
position: fixed;
color: #3498db;
text-align: center;
}
#pagebottom:hover {
opacity: 1;
}
EDIT This is a jQuery solution. There are some great CSS only solutions above.
You can't display your div as none, as it will have no width or height, and therefore be un-hoverable. However, you can use the opacity attribute, and modify the footer's CSS accordingly.
Take a look at this JSFiddle
Here are the changes I made:
I added opacity: 0; to the #pagebottom CSS so it is invisible by default.
I added the following jQuery:
$('#pagebottom').mouseenter(function(){
$('#pagebottom').css('opacity','1');
});
$('#pagebottom').mouseleave(function(){
$('#pagebottom').css('opacity','0');
});
This code waits until the mouse enters the div area, and sets the opacity to 1. When the mouse leaves, it sets the opacity to 0 again, making the element invisible.
If you want a nice tradition so the div fades in and out, you can use CSS transitions or a jQuery plugin like Transit, or even the animate feature that Felix describes in his answer.
You can use:
1) css() to set the opacity of your div:
2) hover() to keep track of when the mouse pointer enters and leaves your div
3) animate() to apply fadeIn() and fadeOut animation when changing the opacity
$('#pagebottom').css('opacity','0');
$( "#pagebottom" ).hover(
function() {
$('#pagebottom').stop().animate({opacity: 1}, 500);
}, function() {
$('#pagebottom').stop().animate({opacity: 0}, 500);
}
);
Fiddle Demo

How to put a cross mark in a check box instead of a tick mark? [duplicate]

I am trying to style a checkbox using the following:
<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />
But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?
UPDATE:
The below answer references the state of things before widespread availability of CSS 3. 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:
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
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, that writer found 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.
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. Firefox + Internet Explorer will still allow the checkboxes to function, just unstyled, 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
$(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;
}
.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;
}
/* Large checkboxes */
.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;
}
/* Custom checkbox */
.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%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
<tr>
<td>Normal:</td>
<td><input type="checkbox" /></td>
<td><input type="checkbox" checked="checked" /></td>
<td><input type="checkbox" disabled="disabled" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" /></td>
</tr>
<tr>
<td>Small:</td>
<td><input type="checkbox" class="myinput" /></td>
<td><input type="checkbox" checked="checked" class="myinput" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput" /></td>
</tr>
<tr>
<td>Large:</td>
<td><input type="checkbox" class="myinput large" /></td>
<td><input type="checkbox" checked="checked" class="myinput large" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput large" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large" /></td>
</tr>
<tr>
<td>Custom icon:</td>
<td><input type="checkbox" class="myinput large custom" /></td>
<td><input type="checkbox" checked="checked" class="myinput large custom" /></td>
<td><input type="checkbox" disabled="disabled" class="myinput large custom" /></td>
<td><input type="checkbox" disabled="disabled" checked="checked" class="myinput large custom" /></td>
</tr>
</table>
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;
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";
}
<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" />
<span></span>
<br>
<input type="checkbox" checked="checked" class="flipswitch" />
<span></span>
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:
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.
With the control hidden, you will still need to be able to detect and toggle its checked state.
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 that using CSS3 pseudo-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.
Wrap your checkbox in a label element. This will mean that even when it is hidden, you can still toggle its checked state by clicking anywhere within the label.
Hide your checkbox.
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 dependent 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 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>
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 don't want to use background images!
Well, this is where CSS3's pseudo-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 */
}
/* 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>
There is a way to do this using just CSS. We can (ab)use the label element and style that element instead. The caveat is that this will not work for Internet Explorer 8 and lower 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>
I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
CODEPEN
Steps
Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
Add :focus style to make the checkbox accessible.
Done
Here is how I did it.
.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>
Much more stylish 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>
Modern accessible solution - use accent-color
Use the new accent-color property and make certain to meet a proper contrast ratio of 3:1 to ensure accessibility. This also works for radio buttons.
.red-input {
accent-color: #9d3039;
height: 20px; /* not needed */
width: 20px; /* not needed */
}
<input class="red-input" type="checkbox" />
<!-- Radio button example -->
<input class="red-input" type="radio" />
Old answer, I only recommend this if you need more customization than the above offers:
I have been scrolling and scrolling and tons of these answers simply throw accessibility out the door and violate WCAG in more than one way. I threw in radio buttons since most of the time when you're using custom checkboxes you want custom radio buttons too.
Fiddles:
Checkboxes - pure CSS - free from 3rd party libraries
Radio buttons - pure CSS - free from 3rd party libraries
Checkboxes* that use FontAwesome but could be swapped with Glyphicons, etc. easily
Late to the party but somehow this is still difficult in 2019, 2020, 2021 so I have added my three solutions which are accessible and easy to drop in.
These are all JavaScript free, accessible, and external library free*...
If you want to plug-n-play with any of these just copy the style sheet from the fiddles, edit the color codes in the CSS to fit your needs, and be on your way. You can add a custom svg checkmark icon if you want for the checkboxes. I've added lots of comments for those non-CSS'y folks.
If you have long text or a small container and are encountering text wrapping underneath the checkbox or radio button input then just convert to divs like this.
Longer explanation:
I needed a solution that does not violate WCAG, doesn't rely on JavaScript or external libraries, and that does not break keyboard navigation like tabbing or spacebar to select, that allows focus events, a solution that allows for disabled checkboxes that are both checked and unchecked, and finally a solution where I can customize the look of the checkbox however I want with different background-color's, border-radius, svg backgrounds, etc.
I used some combination of this answer from #Jan Turoň to come up with my own solution which seems to work quite well. I've done a radio button fiddle that uses a lot of the same code from the checkboxes in order to make this work with radio buttons too.
I am still learning accessibility so if I missed something please drop a comment and I will try to correct it.
Here is a code example of my checkboxes:
input[type="checkbox"] {
position: absolute;
opacity: 0;
z-index: -1;
}
/* Text color for the label */
input[type="checkbox"]+span {
cursor: pointer;
font: 16px sans-serif;
color: black;
}
/* Checkbox un-checked 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;
}
/* Checked checkbox style (in this case the background is green #e7ffba, change this to change the color) */
input[type="checkbox"]:checked+span:before {
/* NOTE: Replace the url with a path to an SVG of a checkmark to get a checkmark icon */
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;
/* The size of the checkmark icon, you may/may not need this */
background-size: 25px;
border-radius: 2px;
background-color: #e7ffba;
color: white;
}
/* Adding a dotted border around the active tabbed-into checkbox */
input[type="checkbox"]:focus+span:before,
input[type="checkbox"]:not(:disabled)+span:hover:before {
/* Visible in the full-color space */
box-shadow: 0px 0px 0px 2px rgba(0, 150, 255, 1);
/* Visible in Windows high-contrast themes
box-shadow will be hidden in these modes and
transparency will not be hidden in high-contrast
thus box-shadow will not show but the outline will
providing accessibility */
outline-color: transparent; /*switch to transparent*/
outline-width: 2px;
outline-style: dotted;
}
/* Disabled checkbox styles */
input[type="checkbox"]:disabled+span {
cursor: default;
color: black;
opacity: 0.5;
}
/* Styles specific to this fiddle that you do not need */
body {
padding: 1em;
}
h1 {
font-size: 18px;
}
<h1>
NOTE: Replace the url for the background-image in CSS with a path to an SVG in your solution or CDN. This one was found from a quick google search for a checkmark icon cdn
</h1>
<p>You can easily change the background color, checkbox symbol, border-radius, etc.</p>
<label>
<input type="checkbox">
<span>Try using tab and space</span>
</label>
<br>
<label>
<input type="checkbox" checked disabled>
<span>Disabled Checked Checkbox</span>
</label>
<br>
<label>
<input type="checkbox" disabled>
<span>Disabled Checkbox</span>
</label>
<br>
<label>
<input type="checkbox">
<span>Normal Checkbox</span>
</label>
<br>
<label>
<input type="checkbox">
<span>Another Normal Checkbox</span>
</label>
I'd follow the advice of SW4's answer. Not anymore: Volomike's answer is far superior to all the answers here (note my suggested improvement in the comment to the answer). Proceed reading this answer if you are curious about alternative approaches, which this answer comments.
First of all, hide the checkbox and to cover it with a 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 by 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. The well styled checkbox should follow this behavior.
cobberboy's answer recommends Font Awesome which is usually better than bitmap since fonts are scalable vectors. Working with the HTML above, I'd suggest these CSS rules:
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 a bulletproof way to hide it and convince the browser to use tabindex, so it is a good alternative. Anyway, both is just a hack. The proper way today is appearance: none, see Joost's answer:
input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
}
Style checkbox label
input[type="checkbox"] + span {
font: 16pt sans-serif;
color: #000;
}
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).
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.
Add focus outline
input[type="checkbox"]:focus + span:before {
outline: 1px dotted #aaa;
}
Safari doesn't provide this feature (see #Jason Sankey's comment), see this answer for Safari-only CSS
Set gray color for disabled checkbox
input[type="checkbox"]:disabled + span {
color: #999;
}
Set hover shadow on non-disabled checkbox
input[type="checkbox"]:not(:disabled) + span:hover:before {
text-shadow: 0 1px 2px #77F;
}
Test it on JS Fiddle
Try to hover the mouse over the checkboxes and use Tab and Shift+Tab to move and Space to toggle.
With pure CSS, nothing fancy with :before and :after, no transforms, you can turn off the default appearance and then style it with an inline background image like the following example. This works in Chrome, Firefox, Safari, and now 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 & Conditions</label>
</form>
The CSS Basic User Interface Module Level 4 adds support for this (finally) via a new solution called accent-color, and it's actually quite simple, unlike pretty much every other answer here:
input {
accent-color: rebeccapurple;
}
<input type="checkbox" />
Simply set whatever CSS color (e.g. named value, hex code, etc.) you want in as the value of accent-color, and it will be applied.
This currently works in Chrome (v93+), Edge (v93+), Firefox (v92+), Opera (v79+), and Safari (v15.4+).
Note: Edge, Chrome, and Opera (and possibly Safari; I can't test that) currently don't support alpha channel values via rgba() either (the RGB values of rgba() will still "work"; the alpha channel will simply be ignored by the browser). See MDN Browser Support for more information.
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:
You don't need external libraries and files
You don't need to add
extra HTML in your page
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:
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>
You can style checkboxes with a little trickery using the label element an example is 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>
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!
You can avoid adding extra markup. This works everywhere except IE 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" />
Recently I found a quite interesting solution to the problem.
You could use appearance: none; to turn off the checkbox's default style and then write your own over it like described 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 browser support is quite bad for the appearance option. From my personal testing I only got Opera and Chrome working correctly. But this would be the way to go to keep it simple when better support comes or you only want to use Chrome/Opera.
Example JSFiddle
"Can I use?" link
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.)
As with other solutions, it uses the label element. An adjacent span holds our checkbox character.
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;
}
<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>
Here's the JSFiddle for it.
My solution
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>
You can simply use appearance: none on modern browsers, so that there is no default styling and all your styles are applied properly:
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;
}
Here is a simple CSS solution without any jQuery or JavaScript code.
I am using FontAwseome 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;
}
From my googling, this is the easiest way for checkbox styling. Just add :after and :checked:after CSS based on your design.
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>
Modify the checkbox style with plain CSS. This does not require any JavaScript or 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>
Yikes! All these workarounds have led me to the conclusion that the HTML checkbox kind of 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.
SCSS / SASS Implementation
A more modern approach
For those using SCSS (or easily converted to SASS), the following will be helpful. Effectively, make an element next to the checkbox, which is the one that you will style. When the checkbox is clicked, the CSS restyles the sister element (to your new, checked style). Code is below:
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>
A simple and lightweight template as well:
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/
I think the easiest way to do it is by styling a label and making the checkbox invisible.
HTML
<input type="checkbox" id="first" />
<label for="first"> </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 its 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 Internet Explorer understand ::checked on the checkbox.
Here's a modern version with a little animation, and simple styling you can customize:
.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);
}
No JavaScript or jQuery required.
Change your checkbox style simple way.
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;
}
<input type="checkbox" id="option" />
<label for="option"> <span></span> Click me </label>
Here is a JSFiddle link
Custom checkbox with CSS (WebKit browser solution only Chrome, Safari, Mobile browsers)
<input type="checkbox" id="cardAccptance" name="cardAccptance" value="Yes">
<label for="cardAccptance" class="bold"> Save Card for Future Use</label>
CSS:
/* The checkbox-cu */
.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;
}
/* Hide the browser's default checkbox-cu */
.checkbox-cu input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox-cu */
.checkmark {
position: absolute;
top: 4px;
left: 0;
height: 20px;
width: 20px;
background-color: #eee;
border: 1px solid #999;
border-radius: 0;
box-shadow: none;
}
/* On mouse-over, add a grey background color */
.checkbox-cu:hover input~.checkmark {
background-color: #ccc;
}
/* When the checkbox-cu is checked, add a blue background */
.checkbox-cu input:checked~.checkmark {
background-color: transparent;
}
/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.checkbox-cu input:checked~.checkmark:after {
display: block;
}
/* Style 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;
}
By using Materialize with a custom stylesheet, you can achieve something like this:
CSS code
.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 code
<label>
<input type="checkbox" class="custom_checkbox" />
<span>Text</span>
</label>
Demo
JSFiddle demo
This helped me to change style (color) for checkbox
input[type=checkbox] {
accent-color: red;
}
We can also use the same for radio buttons.
This is simplest way and you can choose which checkboxes 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>
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, ASP.NET (.aspx), JavaServer Faces, and ColdFusion too.

Categories