At the moment, there is no direct way to apply styles to a parent element using CSS.
One workaround is to utilize JavaScript/jQuery to style the parent element.
$('input').parent();
However, in the near future, a :has()
pseudo-class will be introduced, allowing for styling of parent elements like so:
div:has(>input)
, which will target all divs containing a child <input>
.
If you prefer not to rely on JavaScript, the HTML structure needs to be modified.
By making the div a sibling of the input field, you can then use the sibling combinators:
The +
symbol selects only the immediate adjacent sibling, while the ~
symbol targets any following sibling.
It's important to mention that targeting previous siblings is not supported.
Take a look at this demonstration:
input ~ div {
background-color: green;
}
input + div {
color: white;
}
<div>div not selected</div>
<input type="text" id="name" />
<div>div selected by both sibling combinators</div>
<div>div selected only by the general sibling combinator</div>
<div>selected also only by the general sibling combinator</div>