I want to change the style of the parent element when there is a focus in the child element input.
I know that the original CSS doesn't work. I can use the state because it is React, but I want to know if there is a simpler way.
<div className="container">
<div className="input__container">
<input type="text">
</input>
</div>
</div>
input:focus .container {
border: 1px solid blue;
}
CodePudding user response:
You can use the has()
pseude code. Please note however that it's not yet supported by Firefox.
.input__container {
width: 200px;
height: 100px;
background: blue;
}
.input__container:has(input:focus) {
background: red;
}
<div >
<div >
<input type="text">
</div>
</div>
CodePudding user response:
Use the :focus-within
pseudo class (the :has
pseudo class - which has less browser support isn't necessary here)
From MDN:
The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused.
Also, browser support is very good
.container {
border: 5px solid gold;
display: inline-block;
}
.container:focus-within {
border: 5px solid green;
}
<div >
<div >
<input type="text">
</input>
</div>
</div>