Day 22: Checkbox 🧦

Category: Advent of UI components

Published at:

A checkbox component is a form item used when multiple selectable objects are in a list.

The example component is visible below.



A few notes about this notification component:

  • CSS Variables are used for colors and spacing,
  • CSS Flexbox is used for layout,
  • the before and after components are used to style the checkbox,
  • the :checked selector is used to determine if the checkbox is checked,
  • the ~ sibling selector is used to target the sibling label,
  • the inline SVG is used to add a custom checkbox.

The code:

<div class="advent-checkbox">
  <input type="checkbox" id="checkbox1" name="checkbox1" checked>
  <label for="checkbox1">Christmas tree 🎄</label>
</div>
<div class="advent-checkbox">
  <input type="checkbox" id="checkbox2" name="checkbox2" checked>
  <label for="checkbox2">Fireplace 🔥</label>
</div>
<div class="advent-checkbox">
  <input type="checkbox" id="checkbox3" name="checkbox3" checked>
  <label for="checkbox3">Socks 🧦</label>
</div>
.advent-checkbox {
  --color-xmas-alpha: #f7efef;
  --color-xmas-beta: #d72621;
  --color-xmas-gamma: #639565;
  --size-xmas: 1em;

  position: relative;
  margin-bottom: var(--size-xmas);
  padding: calc(var(--size-xmas) / 6) calc(var(--size-xmas) / 3);
  overflow: hidden;
}

.advent-checkbox input[type="checkbox"] {
  position: absolute;
  left: -100vw;
}

.advent-checkbox label {
  color: var(--color-xmas-beta);
  display: inline-flex;
  align-items: center;
  position: relative;
  cursor: pointer;
}

.advent-checkbox input[type="checkbox"]:checked ~ label {
  color: var(--color-xmas-gamma);
}

.advent-checkbox label:before,
.advent-checkbox label:after {
  content: "";
  display: inline-block;
  min-height: var(--size-xmas);
  min-width: var(--size-xmas);
}

.advent-checkbox label:before {
  background-color: var(--color-xmas-alpha);
  border: 1px solid currentColor;
  border-radius: calc(var(--size-xmas) / 4);
  margin-right: calc(var(--size-xmas) / 2);
}

.advent-checkbox label:after {
  background-position: center;
  background-repeat: no-repeat;
  background-size: calc(var(--size-xmas) / 2);
  position: absolute;
  left: 0;
}

.advent-checkbox input[type="checkbox"]:checked ~ label:after {
  background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'><path d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z'/></svg>");
}

.advent-checkbox input[type="checkbox"]:focus ~ label:before {
  outline: 1px solid currentColor;
  outline-offset: calc(var(--size-xmas) / 4);
}