Issue
I created a range input in my markup, and set its value to 0, like so:
<input type="range" min="0" max="100" step="10" value="0">
I want to style it based on its current value. Let's say I want to give it a margin-top of 50px if its value is "10". I write the following simple CSS rule:
[type="range"][value="10"] {
margin-top: 50px;
}
When sliding the range input to 10, one expects the rule to fire, but it doesn't. It does however fire when setting the input's value to "10" in the markup.
Am I missing something here? Is there really no way to style a range input according to its value, as dynamically changed by the user, with CSS only?
Solution
The value of the input and the value attribute are 2 separate things. The value attribute represents the initial value of the element specified in your HTML. CSS can only target that attribute, and unfortunately can't target the actual value of the element. However, you can use javascript to read the current value on change, then update the value attribute with the value of the input, then you can target that updated attribute in CSS.
document.getElementById('input').addEventListener('change',function() {
this.setAttribute('value',this.value);
});
input[type="range"][value="10"] {
margin-top: 10px;
}
input[type="range"][value="20"] {
margin-top: 20px;
}
<input id="input" type="range" min="0" max="100" step="10" value="0">
Answered By - Michael Coker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.