Styling range input with CSS and JavaScript for better UX
To style the range input with CSS you’ll need to apply styles to two pseudo-elements: ::-webkit-slider-thumb and ::-webkit-slider-runnable-track . Find out how you can apply custom styling and make the range input more functional and appealing.
Contents of the article:
The input element with a type of range is a native HTML form UI element that allows users to select a value by dragging a slider over a range field.
The default browser styling for this element is very basic and doesn’t provide enough information to the user which might confuse one. Also, the appearance of the range input element is different across browsers.
Range input HTML:
Range input appearance on different browsers:
Chrome
Edge
Firefox
Safari
Luckily there are ways you can improve that using nothing but native CSS and JavaScript.
CSS selectors for the range input
The range input widget consists of two parts the thumb and the track. Each one of these parts has its own pseudo-class selector for styling with a vendor suffix for cross-browser support.
Thumb:
Track:
To indicate the selected value, we can add a color from the start of the track up until the thumb. To do that we can use the background-image property with the linear-gradient() value. The background-size property will be used to set the size, which can later be updated with JavaScript.
Improving usability
The default range input doesn’t specify any values selected. Which makes it hard for users to understand what value is currently selected.
While the hash marks and labels on the range input are a great way to aid users visually, this feature is yet to become available.
However, there are a few ways you can improve that with some additional HTML and JavaScript:
- Specify the output element to display the selected value
- Specify the number input that is synced to the range input
Specify the output element to display the selected value
The output element on the side of the range input will display the selected value. You’ll have to add an id attribute for the output element, and an oninput attribute for the range input with a short function as a value, that will update the output element contents.
Specify the number input that is synced to the range input
To take it a step further you can add a number input next to the range element.
That way the user will see the selected value and will have an option to modify it via the number input, which can be a better experience especially for mobile users.
A sprinkle of JavaScript
To finalize we’ll need some JavaScript code to make it all work. The oninput attribute is already updating value based on a target element.
But to update the selected area of the range input we need to calculate the ratio and apply that value to the input background-size property.
NOTE: the value property of the range input is a string type, if you want to use is as a numeric value you should use valueAsNumber property.
Как стилизовать input range

- Главная /
- CSS /
- Стилизация ползунка
Стилизация ползунка

Добрый день! Тема сегодняшней рубрики css — стилизация ползунка(поля range). Итак, приступим к рассмотрению!
Для начала создадим ползунок:
Видим ползунок со стандартными стилями, причем в разных браузерах он будет отображаться по разному.
Зададим ему ширину 200px.
Здесь помимо ширины мы указали специальное свойство appearance которое отвечает за базовые стили отображения элемента вашей операционной системы. Значение 'none' указывает на то что мы эти стили сбрасываем. По итогу поле range будет отображаться не полностью. Это нам необходимо чтобы задать свои собственные стили для ползунка. Заметьте что вместе со свойством 'appearance' мы используем вендорные префиксы -webkit — Для браузеров на движке хромиум(google chrome) и -moz — для браузера mozilla firefox. Сразу отмечу что мы нацелены только на современные браузеры без всяких там IE(Internet Explorer).
Теперь давайте попробуем стилизовать ползунок, делается это через специальные псевдоселекторы.
Для браузеров webkit(google chrome, chromium) используются псевдоселекторы -webkit-slider-runnable-track, -webkit-slider-thumb, а для mozilla firefox -moz-range-track, -moz-range-thumb.
track — на конце каждого псевдоселектора отвечает за стилизацию полосы ползунка, а thumb за сам элемент ползунка. Отображение в разных браузерах может немного отличаться но в целом по стилистике будет одинаковым. Можете взять пример и поиграться со стилями!
Еще один пример стилизации:
Здесь получили другое отображение ползунка с эффектом выделения выбранного диапазона.
На этом в принципе у меня все. Если статья оказалась для вас полезной, подписывайтесь на группу Вконтакте и переходите на мой канал Youtube.
Всем удачи и здоровья!
Оцените статью:
Статьи
Комментарии
Внимание. Все комментарии проходят модерацию перед публикацией!
В данном разделе пока нет комментариев!

Запись экрана
Данное расширение позволяет записывать экран и выводит видео в формате webm
Styling Cross-Browser Compatible Range Inputs with CSS
Styling for range inputs has improved dramatically since the release of IE 10. It is now possible to generate cross-browser compatible range inputs (sliders) using only CSS. In this tutorial, we will take a basic range input ( <input type=»range»> ):
Screenshot of a range input, Mac Chrome 38
And turn it into this:
Range input with completely custom styles.
In order to simplify the process of generating cross-compatible styles, LESS style sheets have been included. CSS is also available.
Applying base CSS styles
Several styles need to be applied to range inputs in all browsers to override their basic appearance.
This gives us invisible or unstyled range inputs in all browsers. Now we can apply our custom styles.
Styling the Thumb
The widget that you click or drag along the track is called the thumb. It can be styled just like a regular HTML element.
Note that while we’re repeating code here, that’s necessary as you can’t comma-separate these type of selectors. Browsers will drop the entire selector if it doesn’t understand a part of it.
This gives us the following:
A styled input on an invisible track (WebKit/Blink) or an unstyled track (Firefox and IE)
Styling the Track
The line that the thumb moves across is called the track. It is also styled just like a regular HTML element.
A note on IE: Internet Explorer 10+ has a slightly different approach to range inputs. In IE, you are allowed to specify completely different styles for the upper (right of the thumb) and lower (left of the thumb) areas of the track.
Another thing to note is that you can apply focus effects to the track which change the styling when the user is interacting with the range.
The code above gives us:
a track with no thumb (Chrome) or an unstyled thumb (Firefox and IE)
Building a Complete Range Input
Now that we’ve built a thumb and a track, we can combine the CSS together and make the completed range input.
Full CSS to Style Range Inputs in All Browsers
The full CSS for the styled range inputs in all browsers is below.
Completed Range Input
These styles make the following input:
Range input with completely custom styles.
Bonus: Full Less to Style Range Inputs in All Browsers
There is a lot of CSS required to make identical range inputs for each browser. Using a preprocessor, you can achieve much more efficient results. Included below is the .less file used to generate the CSS above.
Bonus 2: Sass Version!
The range input itself has browser support about like: Firefox 23+, Safari 4+, iOS 5+, Chrome 6+, Opera 11+, IE 10+, Android 4.2+. So pretty good. This custom styling stuff should largely match that if you follow the code in this article.
Here’s a screenshot from a demo in lots of current versions of browsers:

If a browser doesn’t support range inputs, you’ll just get a text input, which is still functional and valid.
As cross-browser range input styles only became viable in 2014, there are not many tools yet to generate modern styles. range.css is a useful tool for generating CSS styles for range inputs that I created.
Comments
This is good. Now if only people would make selects styleable we’ll be in good shape.
Are referring to Firefox and the non-removable drop-down arrow? Otherwise they are able to be styled.
I think @ElijahFowler is talking about creating a pseudo-element selector to style the select button directly like an input button. Something like select::arrow-button.
Currently you can do something similar with:
input[type=”file”]::-webkit-file-upload-button
input[type=number]::-webkit-inner-spin-button
input[type=number]::-webkit-outer-spin-button
input[type=range]::-webkit-slider-thumb
Maybe this can help you:
http://jsfiddle.net/keu0c29w/
This is not full example, but only the base.
Is there any way to make the slider vertical while keeping the custom styling?
input[type=range] <
transform: rotate(90deg);
>
How about combining a range slider with a progress bar?
As a fresher new to designing I need to be get updated with so many things like this. Thanks a lot for letting me know this. Let me work on it.
Looks like a good solution for custom style instead of default browser style. Thanks for sharing this awesome tips. One thing, How can I style custom file input box for all browser?
Ya the best way I’ve found to do it is to hide it and show another element that basically controls it. I use some basic javascript to trigger it when the controller is clicked. As far as I know, there’s no super awesome way to do it without some Javascript.
I do it with pure CSS, but to be able to show the filename we need to use JavaScript. In theory input[type=file]::after with content: attr(value) could work, but input is not suppose to have children so ergo no :before / :after .
We can use the same technique as for when we do custom radio/checkboxes, by using the label as the acting button.
HTML
CSS
Neat solution. I’ve tried similar styling in the past but have found myself that people find OS controls easier to use/understand if they are left alone. Anis, file inputs are pretty much impossible to style. Best thing is to make the file input opacity 0, then create your custom version and using javascript capture the details. good example here: http://geniuscarrier.com/how-to-style-a-html-file-upload-button-in-pure-css/
Unfortunately we still have these vendor prefixes. At the moment I would still stick to a javascript slider built with non-semantic elements.
most Javascript solutions do not support touch (on all platforms), mobile (again on all platforms) or are probably at least partly or not accessible at all.
And what is the point, a native slider might look a bit different on different platforms but at least (should) work for all and well. I’d always stick to built in solutions which also improve if the browsers improve.
I am facing compatability issue in IE browser..What exact the prob i am stating …in our application home page which is topcatagory display page have one back ground image at left side and we have 4 content spots(text content) as well…Generally these content spots are like alerts every day ..if we apply all content spots (text content) the image is looking fine in IE and fire fox browser.In this case image size is increasing proposhinate to the text..when we remove 2 text content that back ground image is lacking some part of image on IE and fire fox..when we removed all the contents on the page even the image in going up only visable half of the image.More over this image is lacking much on IE browser for fire fox i have set min-height prop for back ground but the same is not reflecting in IE..any one could help on this ..Your quick reply would be highly appreciated.thanks in advance.
even i have tried to removed and add min-height in my code with the same reflecting on fire fox and able to see the image properly but not in IE10 and IE8 ..Could you please help how would i apply the same for IE browser…Thank you.
Awesome, thanks for this helpful share. Its very important to cross browser check even after these changes are made. Luckily, I haven’t had many problems with IE lately which is very nice, they are either doing a better job with updating or my css is more compatible!
Just running though the tutorial, IE seems to be happy enough for once. Going back to the comment about customizing the input field. Does anyone have any examples of how to do this with JS? – Thanks
How to customize the HTML5 input range type looks using CSS?
I want to customize the looks of the range input type in HTML5 to look something like a progress bar. I’ve tried applying some common CSS attributes using CSS class but it seems that they are not working.
Can any one direct me how to customize it??
![]()
10 Answers 10
If you’re using HTML 5, why not use the progress tag?
EDIT: nowadays all major browser support both
Hence you should use one of these two, as explained in other answers, and this should not be the accepted answer anymore.
The <input type=»range»> is pretty new and you are already attempting to customize it with CSS. 🙂
I wouldn’t try that for two reasons:
there might be huge compatibility issues now and for the next few (or many) years. Think that in nowadays a form control like <select> (available since the web started) is still problematic to be customized with CSS in a cross browser way. For instance if you set a padding for the select boxes, many browser (IE7, OPERA9, CHROME5, SAFARI4) will totally ignore the padding. It works only IE8 and on FF 3.6. (all tests done with HTML5 DOCTYPE so in standard mode).
The <input type=»range»> has been created to show a slider NOT a progress bar, attempting to cheat on it with CSS in order to transform a slider into progress bar it sounds bizarre. Like trying to use CSS to change a <textarea> into a table, but why don’t you simply use a <table> to render tables?!
To show a progress bar in HTML5 you should follow the suggestion given by marcgg in his answer. Since no browser is currently rendereing it you could use a simple div with a p inside like this: