Explain Codes LogoExplain Codes Logo

How to style a checkbox using CSS

html
responsive-design
css
web-development
Nikita BarsukovbyNikita Barsukov·Oct 11, 2024
TLDR

Hide the base checkbox, and employ a stylized <label> for visual enhancement:

<input type="checkbox" id="cb" hidden /> <label for="cb" class="custom-cb"></label>
.custom-cb { display: inline-block; width: 20px; height: 20px; background: #ddd; } .custom-cb::before { content: ''; display: none; position: absolute; width: 12px; height: 12px; background: white; } #cb:checked + .custom-cb::before { display: block; }

Step up the game: Advanced checkbox customization

Crafting art with CSS pseudo-elements

Ditch the basic box! Use ::before and ::after pseudo-elements for custom checkbox symbols.

.custom-cb::after { content: '✔'; display: none; color: green; font-size: 18px; position: absolute; top: 0; left: 4px; } #cb:checked + .custom-cb::after { display: block; }

Tada! A green checkmark appears when checkbox is picked.

Nailing interactivity with state-specific stylings

For the smooth sailing of users, extend styles for :hover, :focus, and :disabled states.

.custom-cb:hover { box-shadow: 0 0 3px #666; /* Because shadows speak of depth */ } .custom-cb:focus { outline: 2px solid blue; /* Now you can't lose focus! */ } #cb:disabled + .custom-cb { opacity: 0.5; /* Fade away when I'm not needed */ }

These cues help users aim right and inform about checkbox state.

Embracing SVGs for top-notch graphics

For crystal clear visuals on all devices, cue SVGs as background images.

input[type="checkbox"]:checked { background: url('checkmark.svg') no-repeat center center; /* Because pixels are so passé */ background-size: contain; /* Just making sure the size is right */ }

Thanks to SVG's scalability, quality never dips!

Beyond basic: Deep dive into customization

Prioritizing accessibility

Adopt a contrast ratio of 3:1 for visually challenged users.

.custom-cb { border: 2px solid #555; /* Dark enough to spot from space */ }

Better to pair checkboxes with labels for screen readers.

<label for="cb" class="custom-cb">Option</label>

Catering to diverse design

All checkboxes aren't created equal. Accommodate .large and others for size variants.

.custom-cb.large { width: 30px; height: 30px; /* The big cheese of checkboxes */ }

Baking in legacy browser compatibility:

/* IE8 and below compatibility */ input[type="checkbox"] { /* Think of this as your browser time machine */ }

Winning the cross-browser game with progressive enhancement.