0

I am trying to make a custom slider for which I have found a sample code. I have customized it a bit as per my needs but unable to set the width of the slider range element appropriately.

enter image description here

The size and transformation calculations are defined in em units in using SCSS. I can set the width for $track-w in SCSS the slider is wide enough for my screen size but it comes differently for other screens. Below is the code.

$track-w: 55em; //this width is not responsive
$track-h: .25em;
$thumb-d: 1.5em;
$dist: $track-w - $thumb-d;

@mixin track() {
    box-sizing: border-box;
    border: none;
    width: $track-w;
    height: $track-h;
}

.wrap {
    display: flex;
    align-items: center;
    position: relative;
    width: $track-w;
    height: 3.5*$thumb-d;
    font: 1em/1 arial, sans-serif
}

[type='range'] {
    &, &::-webkit-slider-thumb {
        -webkit-appearance: none
    }

    flex: 1;
    margin: 0;
    padding: 0;
    min-height: $thumb-d;
    background: transparent;
    font: inherit;

    &::-webkit-slider-runnable-track {
        @include track()
    }
    &::-moz-range-track { @include track }
    &::-ms-track { @include track }

    &::-webkit-slider-thumb {
        margin-top: .3*($track-h - $thumb-d);
    }
    &::-ms-thumb {
        margin-top: 0;
    }

    &::-ms-tooltip { display: none }

    ~ output {
        display: none;

        .js & {
            display: block;
            position: absolute;
            left: .5*$thumb-d; top: 0;
            padding: .25em .5em;
            border-radius: 3px;
            transform: translate(calc((var(--val) - var(--min))/(var(--max) - var(--min))*#{$dist} - 50%));
            background: #4285f4;
            color: #eee;
        }
    }
}

Here is the codepen link-https://codepen.io/thebabydino/pen/WdeYMd for the sample output and more details. How can I make the slider responsive? Please let me know if I can provide more details.

Souvik Ghosh
  • 4,456
  • 13
  • 56
  • 78

2 Answers2

0

The unit Em is merely responsive to the size of the font (of the element, Rem is of the root). To scale this you have to scale the font size.

Instead you can use other responsive units such as vw for view-width or vh for view-height (and vmin and vmax) or % (which comes with a bit of knowing how parents, position and display impact that)

Here's more info about units in css

Since a slider is more wide than high I suppose you could change the em for vw and play around with the values a bit.

See: https://codepen.io/anon/pen/RYzpdx This will be responsive as in always 50% of the page wide (I did add a 25vw margin to the left to center it, to show it off a bit beter)

$track-w: 50vw;
$track-h: .25vw;
$thumb-d: 1.5vw;
Grenther
  • 476
  • 3
  • 10
0

Use for the responsive div

.your-class {
  max-width: 44em/px etc.
  width: 100%;
}

And will be responsive, and don't forget about @media-query

Carnaru Valentin
  • 1,690
  • 17
  • 27