Changing background color on input focus with css alone
16,110
Solution 1
You cannot select a parent element with CSS.
However. you can fake something similar with a box shadow
body {
margin: 25px; /* not required */
}
.input-name:focus {
box-shadow:0 0 0 10px red;
}
<div class="name">
<input type="text" class="input-name" />
</div>
Solution 2
Unfortunately, you can't select a parent with CSS.
Is there a CSS parent selector?
This will have to be done via script.
(function() {
var inputs = document.getElementsByClassName('input-name');
if( !(inputs && inputs.length) ) return;
function toggleRed(elem) {
elem.classList.toggle('red');
}
for(var i=0; i < inputs.length; i++) {
var input = inputs[i];
// focus
input.addEventListener('focus', function() {
toggleRed(this.parentElement);
});
// blur
input.addEventListener('blur', function() {
toggleRed(this.parentElement);
});
}
})();
Check this for a demo
http://jsfiddle.net/andyw_/6ec1efs2/1/
Author by
Ghostff
Updated on June 09, 2022Comments
-
Ghostff over 1 year
Am trying to change the background color of an input holder once the input is clicked i used these
<div class="name"> <input type="text" class="input-name"></div>
CSS
.input-name:focus + .name{ background:#f00; }
this is how it is normally
this is what i want on focus
but it wont Work