Why is this CSS checkbox slider switch not pixel-perfect?

44 Views Asked by At

This CSS slider switch is:

  • pixel-perfect on my laptop display (~ 1400 x 800 resolution).
  • not pixel-perfect on my 1920 x 1080 display, Winows 10's "Scale and layout" setting to 100%, and browser zoom set to 125%
  • pixel-perfect on my 4k display, Scale and layout = 150 %, browser zoom set to 150%

By "not pixel perfect", I mean that there is some (subpixel) white space between the border and the dark circle:

enter image description here

Changing transparent -9px to another value helps to make the circle closer to the left border, but then we can see the start of a new circle on the right side.

Question: how to have a perfect rendering for this switch, no matter the resolution?

.switch {
  appearance: none;
  padding: 9px 18px;
  border-radius: 13px;
  background: radial-gradient(circle 9px, #001122 100%, transparent 100%) transparent -9px;
  border: 1px solid #001122;
}

.switch:checked {
  background-position: 9px;
}
<input type="checkbox" class="switch">

1

There are 1 best solutions below

4
Temani Afif On

You can never be "perfect" especially using gradients but you can improve it visually but adding some space

.switch {
  --s: 20px; /* control the size */

  appearance: none;
  height: var(--s);
  aspect-ratio: 2;
  border-radius: var(--s);
  background: radial-gradient(50% 50%,#001122 92%, #0000) left/var(--s) 100% no-repeat content-box;
  border: 1px solid #001122;
  padding: 2px; /* control the gap */
  box-sizing: content-box;
}

.switch:checked {
  background-position: right;
}
<input type="checkbox" class="switch">