Ghostff
Ghostff

Reputation: 1458

Changing background color on input focus with css alone

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 enter image description here

this is what i want on focus enter image description here

but it wont Work

Upvotes: 7

Views: 27990

Answers (4)

Constantine
Constantine

Reputation: 21

You can use pseudo-class :has(child) so:

.name:has(.input-name:focus-visible) {
     background:#f00;
}

Upvotes: 2

andyw_
andyw_

Reputation: 500

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/

Upvotes: 1

user4110695
user4110695

Reputation:

While the exact thing you want can't be done, @Paulie_D 's answer was the closest with pure css.

To do exactly what you wanted you would need to use javascript because, as aforementioned, you can't select a parent element.

Here's the javascript:

function myFunction() {
document.getElementById("name").style.background = "red";

}

And the HTML:

<div id="name>
<input type="text" id="input" onfocus="myFunction()">

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 114981

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>

Upvotes: 7

Related Questions