div {
padding: 1em;
}
div:has(input:focus-visible) {
outline: 2px auto red;
border: 0;
}
div:has(input:focus-within) {
border: 1px solid green;
outline: none;
}
<div>
<input/>
</div>
I have a container with an input inside and some other divs. What I want to achieve is when I focus with the keyboard (using Tab) on the input, the container should be outlined with red, and when I directly click on the container, it should be bordered with green. But in this case only green works.
3
Answers
You need JavaScript to achieve the second part of your question, you can add a click event listener on the document and check whether the
inputContainer === e.target
in case you want the effect when clicking on the container only orinputContainer.contains(e.target)
in case you want the effect when clicking on the container or any of its children:You can do it with Javascript event listeners, stopping the bubbling at the right times:
This will create the behavior you describe, which is, if you tab to the
input
, the container with have a red outline. If you click the container, it will have a green border. If, however, you click theinput
, the container will have the red outline, since theinput
has focus, and the div:has
it, so the selector matches.