Skip to content

Instantly share code, notes, and snippets.

@migcarva
Created August 19, 2019 10:13
Show Gist options
  • Save migcarva/32a7437e69134116ae7f10a3b6954112 to your computer and use it in GitHub Desktop.
Save migcarva/32a7437e69134116ae7f10a3b6954112 to your computer and use it in GitHub Desktop.
Custom and Accessible Checkbox
<div>
<input type="checkbox" id="checkbox" name="checkbox" value="custom and accessible" checked>
<label for="checkbox">Custom and Accessible</label>
</div>
@supports(-webkit-appearance: none) {
/* AKA, only do this if `-webkit-appearance: none` is supported.
Which means IE11 and Opera Mini will get the old browser-styled checkbox.
Which works just fine. Old browsers can get old looking things. */
input[type="checkbox"] {
/* Remove the default styling.
`-webkit-appearance` is not an official CSS property
& likely never will be. But it's also in 95% of browsers,
non-webkit included, yes, as a `-webkit` property.
Firefox, Edge, Chrome, Opera all implemented `-webkit-appearance`.
Plus it *will* stick around. Browsers can't remove it.
So use it like this... */
-webkit-appearance: none;
/* Style the box. */
width: 1.6rem;
height: 1.6rem;
border: 1px solid #808080;
}
input[type="checkbox"]:focus {
/* Style the box when it's focused. */
border: 1px solid teal;
}
input[type="checkbox"]:checked {
/* Prepare for placing the new checkmark. */
position: relative;
/* Do a bug fix to keep iOS from adding dark background. */
background: none;
}
input[id="checkbox"]:checked::after {
/* Place (position) the new checkmark. */
position: absolute;
top: 0.36rem;
left: 0.12rem;
/* Create a checkmark in CSS.
Could use an SVG or `content: "✓";` instead.
This is a box, turned 45 degs, with a
left and bottom border to make the checkmark.
Created using an empty pseudo-element.*/
content: "";
width: 1.0rem;
height: 0.3rem;
border: 4px solid black;
border-right: none;
border-top: none;
transform: rotate(-45deg);
}
}
/* Add a bit of styling to the page & typography. Totally optional. */
body {
margin: 2rem;
font-family: Avenir, Roboto, sans-serif;
}
/* Tweek the vertical alignment.
Might not be needed given the layout context on your site. */
div {
/* If Grid is not supported, all of this code will do nothing.
All will be fine. Nothing will explode. Just won't be as pretty. */
display: grid;
grid-template-columns: min-content 1fr;
gap: 0.6rem;
align-items: center;
}
label {
padding-top: 0.2rem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment