Effectively, in order to be able to be focused, an element needs to be focusable:
An element is focusable if all of the following conditions are
met:
In your case, the problem is the first condition. You can make the div
focusable by setting its tabindex focus flag through a tabindex
attribute.
p:focus {
background: #0f0;
}
<p tabindex="-1">Click me. I can be focused</p>
<p>But I can't :(</p>
However, there is a problem. There can only be one focused element in the document. Therefore, the div
and the input
can't be focused simultaneously.
In fact, you don't want to select the div
when it is focused, you want to select it when it contains a focused element.
The Selectors Level 4 draft addresses this exact problem by creating the new :focus-within
pseudo-class:
9.4. The Generalized Input Focus Pseudo-class:
:focus-within
The :focus-within
pseudo-class applies to elements for which
the :focus
pseudo class applies. Additionally, the ancestors
of an element that matches :focus-within
also match
:focus-within
.
Sadly browsers don't support it yet. So meanwhile, use JS.