Цвет ползунка range css

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.

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:

Range Input on Chrome Range Input on Edge Range Input on Firefox Range Input on Safari

Luckily there are ways you can improve that using nothing but native CSS and JavaScript.

Accent color

One simple way to customize the appearance of the range input without any specific selectors or additional HTML is to change the color of the range.

To do so you can define the accent-color property for the input[type=»range»] selector which will update the color of the track and thumb.

input[type="range"]  accent-color: coral; > 

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.

input[type="range"]  -webkit-appearance: none; margin-right: 15px; width: 200px; height: 7px; background: rgba(255, 255, 255, 0.6); border-radius: 5px; background-image: linear-gradient(#ff4500, #ff4500); background-size: 70% 100%; background-repeat: no-repeat; > input[type="range"]::-webkit-slider-thumb  -webkit-appearance: none; height: 20px; width: 20px; border-radius: 50%; background: #ff4500; cursor: ew-resize; box-shadow: 0 0 2px 0 #555; transition: background .3s ease-in-out; > input[type=range]::-webkit-slider-runnable-track  -webkit-appearance: none; box-shadow: none; border: none; background: transparent; > 

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:

  1. Specify the output element to display the selected value
  2. 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.

 type="range" min="0" max="100" oninput="rangevalue.value=value"/>  id="rangevalue">50 

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.

 type="range" value="50" min="0" max="100" id="range" oninput="rangevalue.value=value"/>  type="number" id="rangevalue" value="50" oninput="range.value=value"> 

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.

const rangeInputs = document.querySelectorAll('input[type="range"]') const numberInput = document.querySelector('input[type="number"]') function handleInputChange(e)  let target = e.target if (e.target.type !== 'range')  target = document.getElementById('range') > const min = target.min const max = target.max const val = target.value target.style.backgroundSize = (val - min) * 100 / (max - min) + '% 100%' > rangeInputs.forEach(input =>  input.addEventListener('input', handleInputChange) >) numberInput.addEventListener('input', handleInputChange) 

Range input for RTL direction

To make the above solution of custom range input work for RTL (right to left) web pages, you must make some adjustments for both CSS and JavaScript.

The recommended way to set the text direction of a block or a whole page is to use the dir attribute.

Once the dir attribute is set, we can specify the following selector for the range input [dir=»rtl»] input[type=»range»] .

Now to set the same value for the RTL direction, we must revet the background colors and the value. So for the 70% range, it will look as follows:

[dir="rtl"] input[type="range"]  /* Used to be gradient color, the current progress */ background: #ff4500; /* Used to be background color, the track */ background-image: linear-gradient(#fff, #fff); /* 30% is the difference between the max and the current value (100 - 70) */ background-size: 30% 100%; background-repeat: no-repeat; > 

As for the JavaScript, we need to add a condition for the change handler function, to calculate the correct value: max — current.

function handleInputChange(e)  let target = e.target if (e.target.type !== 'range')  target = document.getElementById('range') > const min = target.min const max = target.max const val = target.value let percentage = (val - min) * 100 / (max - min) // condition to check whether the document has RTL direction // you can move it to a variable, if document direction is dynamic if (document.documentElement.dir === 'rtl')  percentage = (max - val) > target.style.backgroundSize = percentage + '% 100%' > 

Custom range input Demo

You can find a full demo with a complete code examples on CodePen:

Источник

Оформление кроссбраузерных элементов input с типом range с помощью CSS

От автора: В этой статье мы познакомимся с инструментом range.css, предназначенным для оформления элемента . Данный тип элемента input является непростым в плане оформления, потому что требует непривычного сочетания стандартных селекторов и свойств с нестандартными селекторами, свойствами и вендорными префиксами.

Возможности для стилизации элемента значительно улучшились с момента выхода версии браузера IE10. Теперь стало возможным создавать кроссбраузерные ползунки выбора диапазона (слайдеры), используя для этого только CSS. В этой обучающей статье мы возьмем стандартный элемент input типа range (Скриншот элемента input с типом range в Mac Chrome 38):

И превратим его вот в такой элемент (Оформление элемента input с типом range с помощью собственных стилей):

Онлайн курс по JavaScript

Научитесь создавать приложения со сложными интерфейсами

Это основной язык для современной веб-разработки — почти 100% сайтов работает на JavaScript. Освойте его с нуля всего за 4 месяца, и вы сможете зарабатывать от 70 000 рублей.

Для того чтобы упростить процесс написания кроссбраузерных стилей, мы воспользуемся помощью препроцессора LESS. CSS стили также будут доступны.

Применение базовых CSS стилей

Необходимо применить несколько CSS правил, чтобы изменить отображение элемента input с типом range во всех браузерах.

Источник

How to Style Input Type Range in Chrome, Firefox, and IE

The new HTML5 range input gives you a nifty slider UI component. But of course it looks wildly different and kind of blah across browsers. Don’t worry, you can style input[type=range] in any browser!

The syntax differs from vendor to vendor, but in all cases, you have two components that need to be styled. The track is the long piece representing the range, and the thumb is the nub you slide to pick a value.

It is possible to apply styles directly to input[type=range] , but you may run into cross-browser troubles. Best to take advantage of the vendor specific track and thumb selectors as much as possible. We’ll be using them to recreate this custom styled range slider.

Webkit based browsers (Chrome, Safari, Opera)

In webkit based browsers, the track is styled with a special pseudo selector ::-webkit-slider-runnable-track , and the thumb with ::webkit-slider-thumb .

Custom focus styles can also be applied on the thumb and the track. If you go that route, you’ll have to remove default focus styles on the input itself.

Gotchas

You’ll need to tell webkit you want nothing to do with their default styles by including a -webkit-appearance: none; on both the input and the thumb.

input[type=range] < -webkit-appearance: none; >input[type=range]::-webkit-slider-runnable-track < width: 300px; height: 5px; background: #ddd; border: none; border-radius: 3px; >input[type=range]::-webkit-slider-thumb < -webkit-appearance: none; border: none; height: 16px; width: 16px; border-radius: 50%; background: goldenrod; margin-top: -4px; >input[type=range]:focus < outline: none; >input[type=range]:focus::-webkit-slider-runnable-track

Firefox

In Firefox, the track is styled using the ::-moz-range-track pseduo selector, and the thumb using ::-moz-range-thumb .

Gotchas

There’s currently a little bug in Firefox where outline: none doesn’t remove focus styles. If you have a solid background colour, you can hack a fix by hiding the outline under a border.

You’ll also need to give input[type=range] the same width as your track. It won’t expand to contain the track on it’s own.

input[type=range] < /* fix for FF unable to apply focus style bug */ border: 1px solid white; /*required for proper track sizing in FF*/ width: 300px; >input[type=range]::-moz-range-track < width: 300px; height: 5px; background: #ddd; border: none; border-radius: 3px; >input[type=range]::-moz-range-thumb < border: none; height: 16px; width: 16px; border-radius: 50%; background: goldenrod; >/*hide the outline behind the border*/ input[type=range]:-moz-focusring < outline: 1px solid white; outline-offset: -1px; >input[type=range]:focus::-moz-range-track

Internet Explorer 10 +

Input type range is supported in IE10 and above. We can style the thumb with the ::-ms-thumb pseudo, and the track with ::-ms-track .

Gotchas

IE won’t let the thumb overflow the track, so you’ll have to settle for a taller track that’s at least as big as the thumb.

Update, 15.10.2014: The thumb still can’t overflow the track, but Graham Fowler pointed out a clever workaround. We can fake a wide enough track by adding a thick transparent border on the top and bottom of the track. We’ll also move most of our styles to ::-ms-fill-lower and ::-ms-fill-upper instead of ::ms-track to make sure things like border-radius render correctly.

To remove the default tick marks, you’ll need to set colour: transparent on the track.

Bonus

You can also use ::-ms-fill-lower and ::-ms-fill-upper to further customize the look of the track on either size of the thumb. Here, we’ve enhanced the UI by styling the lower part with a darker grey.

input[type=range]::-ms-track < width: 300px; height: 5px; /*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */ background: transparent; /*leave room for the larger thumb to overflow with a transparent border */ border-color: transparent; border-width: 6px 0; /*remove default tick marks*/ color: transparent; >input[type=range]::-ms-fill-lower < background: #777; border-radius: 10px; >input[type=range]::-ms-fill-upper < background: #ddd; border-radius: 10px; >input[type=range]::-ms-thumb < border: none; height: 16px; width: 16px; border-radius: 50%; background: goldenrod; >input[type=range]:focus::-ms-fill-lower < background: #888; >input[type=range]:focus::-ms-fill-upper

Here’s the full cross-browser code snippet and result.

Источник

Читайте также:  Алгоритм роя частиц python
Оцените статью