Skip to content

Instantly share code, notes, and snippets.

@sneas
Created November 27, 2020 08:56
Show Gist options
  • Select an option

  • Save sneas/05c61dde48b8a7b962ea158895adbe3d to your computer and use it in GitHub Desktop.

Select an option

Save sneas/05c61dde48b8a7b962ea158895adbe3d to your computer and use it in GitHub Desktop.
Style checkbox element. CSS-only. No extra tags or classes required.
// Don't forget to enable autoprefixer.
// The escape-svg() function and checkmark SVG are taken from Bootstrap.
$escaped-characters: (
('<', '%3c'),
('>', '%3e'),
('#', '%23'),
('(', '%28'),
(')', '%29')
) !default;
@function str-replace($string, $search, $replace: "") {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
@function escape-svg($string) {
@if str-index($string, "data:image/svg+xml") {
@each $char, $encoded in $escaped-characters {
// Do not escape the url brackets
@if str-index($string, "url(") == 1 {
$string: url("#{str-replace(str-slice($string, 6, -3), $char, $encoded)}");
} @else {
$string: str-replace($string, $char, $encoded);
}
}
}
@return $string;
}
$checkbox-unchecked-background: #fff;
$checkbox-checked-background: #0098ff;
$checkbox-checkmark-color: #fff;
$checkbox-checkmark-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'><path fill='#{$checkbox-checkmark-color}' d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z'/></svg>");
$checkbox-focus-shadow: 0 0 0 0.2rem rgba($checkbox-checked-background, 0.5);
input[type=checkbox] {
position: relative;
width: 1.5rem;
height: 1.5rem;
vertical-align: middle;
margin: 0 0.5rem 0 0;
appearance: none;
background-color: $checkbox-unchecked-background;
outline: none;
border-radius: 0;
&:after {
content: ' ';
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: $checkbox-checked-background escape-svg($checkbox-checkmark-image) no-repeat center center;
background-size: 50%;
opacity: 0;
transition: opacity .15s ease-in-out;
}
&:checked:after {
opacity: 1;
}
&:focus {
outline: none;
box-shadow: $checkbox-focus-shadow;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment