21 Apr 2023

Using HTML and CSS to create a custom range slider

Range sliders are an essential part of user interface design. They are used to select a value within a range, and they provide a visual indication of the current value. In this blog post, we will walk through the steps of creating a custom range slider using HTML and CSS.

HTML Range Input

The HTML range input is a form element used to create a slider control. It allows the user to select a value within a specified range. Here is the basic syntax for creating an HTML range input:

<input type="range" min="0" max="100" value="50">

In this example, we have created a range input with a minimum value of 0, a maximum value of 100, and an initial value of 50. The slider thumb can be moved by the user to select a value within this range.

Customizing the Slider

The HTML range input has limited styling options. However, we can use CSS to customize the appearance of the slider. Here are some of the properties that we can use to style the slider:

input[type="range"] {
  /* Track styles */
  background-color: gray;
  height: 10px;
  border-radius: 5px;
  /* Thumb styles */
  appearance: none;
  background-color: white;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  box-shadow: 0 0 5px gray;
  /* Thumb position */
  margin-top: -5px;
}

In this example, we have customized the track and thumb styles of the range input. The track is styled with a gray background color, a height of 10 pixels, and a border radius of 5 pixels. The thumb is styled with a white background color, a width and height of 20 pixels, and a border radius of 50%. It also has a box-shadow to give it a raised appearance. Finally, we have adjusted the position of the thumb with a negative margin to center it on the track.

Adding Custom Styles

To create a custom range slider, we can add additional styles to the track and thumb elements. Here is an example of a custom range slider with a blue track and a red thumb:

input[type="range"] {
  /* Track styles */
  background-color: #2196F3;
  height: 10px;
  border-radius: 5px;
  /* Thumb styles */
  appearance: none;
  background-color: #FF5722;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  box-shadow: 0 0 5px #2196F3;
  /* Thumb position */
  margin-top: -5px;
}

In this example, we have set the track background color to a blue color (#2196F3), and the thumb background color to a red color (#FF5722). We have also changed the box-shadow color to match the track color.

Conclusion

In this blog post, we have learned how to create a custom range slider using HTML and CSS. We have explored the HTML range input and its basic styling options. We have also seen how to add custom styles to create a more visually appealing slider. By following these steps, you can create your own custom range slider to use in your projects.