range-input.css icon indicating copy to clipboard operation
range-input.css copied to clipboard

Wrong margin-top unit

Open johnnygerard opened this issue 1 year ago • 1 comments

The margin-top property should not use px units.

When visiting your CSS generator at https://range-input-css.netlify.app/, we see this CSS declaration:

  margin-top: -4px; /* Centers thumb on the track */

When using rem units for the track or thumb heights, this margin will remain the same when a user selects a non-default font-size. The thumb won't be vertically centered.

So it seems that calc should be used for margin-top:

  margin-top: calc((var(--track-height) - var(--thumb-height)) / 2); /* Centers thumb on the track */

johnnygerard avatar Apr 12 '24 04:04 johnnygerard

I created a Sass mixin that replicates the functionality of your CSS generator while providing a fix for the margin-top unit.
The CSS output can be inspected at this Sass playground URL.

@mixin range-input(
  $track-color,
  $track-width,
  $track-height,
  $track-border-radius,
  $thumb-color,
  $thumb-width,
  $thumb-height,
  $thumb-border-radius
) {
  input[type="range"] {
    /*********** Baseline, reset styles ***********/
    -webkit-appearance: none;
    appearance: none;
    background: transparent;
    cursor: pointer;
    width: $track-width;

    /* Removes default focus */
    &:focus {
      outline: none;
    }

    /******** Chrome, Safari, Opera and Edge Chromium styles ********/
    /* slider track */
    &::-webkit-slider-runnable-track {
      background-color: $track-color;
      border-radius: $track-border-radius;
      height: $track-height;
    }

    /* slider thumb */
    &::-webkit-slider-thumb {
      -webkit-appearance: none; /* Override default look */
      appearance: none;
      margin-top: calc(
        ($track-height - $thumb-height) / 2
      ); /* Centers thumb on the track */
      background-color: $thumb-color;
      border-radius: $thumb-border-radius;
      height: $thumb-height;
      width: $thumb-width;
    }

    &:focus::-webkit-slider-thumb {
      outline: 3px solid $thumb-color;
      outline-offset: 0.125rem;
    }

    /*********** Firefox styles ***********/
    /* slider track */
    &::-moz-range-track {
      background-color: $track-color;
      border-radius: $track-border-radius;
      height: $track-height;
    }

    /* slider thumb */
    &::-moz-range-thumb {
      background-color: $thumb-color;
      border: none; /*Removes extra border that FF applies*/
      border-radius: $thumb-border-radius;
      height: $thumb-height;
      width: $thumb-width;
    }

    &:focus::-moz-range-thumb {
      outline: 3px solid $thumb-color;
      outline-offset: 0.125rem;
    }
  }
}

johnnygerard avatar Apr 12 '24 05:04 johnnygerard