Search code examples
cssfocuscss-selectors

Affecting parent element of :focus'd element (pure CSS+HTML preferred)


How can I change the background of a parent <div> when an <input> or <a> is :focus'd (or any other dynamic pseudo-class?

Eg

<div id="formspace">
<form>
<label for="question">
How do I select #formspace for the case when a child is active?</label>
<input type="text" id="question" name="answer"/></form></div>

Solution

  • You can use has():

    div:has(input:focus), 
    div:has(a:focus) {
        background: pink;
    }
    

    Unfortunately css doesn't support parent selectors. :( So the only way to do it is to use javascript like the [jQuery parent method][1].

    Update: CSS Selectors Level 4 will support parent selectors! http://www.w3.org/TR/selectors4/#subject