Positive/Negative Range

Here’s an interesting example of a slider where the range begins at the center of the slider, instead of the ‘min’ or ‘max’ value.

Essentially this is a non-range slider, with a single handle, but we are just creating a pseudo element with CSS to show the range of the slider!

Positive/Negative Range
0%

This demo is based on a question from the Github Discussions forum

Check out the code (svelte & css) below to see how this is possible.

<script>

  let value = 0;
  let min = -100;
  let max = 100;

  // determine if the value is positive or negative, and apply the correct CSS class
  $: cssClass = value > 0 ? "positive" : value < 0 ? "negative" : "";
  // calculate the start position % of the range based on the value
  $: start = Math.abs(max / 2 + value / 2);
  // move the range from either 50%-n% (positive) or n%-50% (negative)
  $: range = value > 0 ? `--right: ${100 - start}%; --left: 50%` : `--left: ${start}%; --right: 50%`;
</script>

<RangeSlider
  id="pos-neg"
  class={cssClass}
  style={range}
  bind:value
  {min}
  {max}
  suffix="%"
  formatter={(v) => (v > 0 ? `+${v}` : v < 0 ? `-${Math.abs(v)}` : v)}
  float
/>