I want to show a div only when:
Here is my HTML:
<div>
<input type="text" />
<div>
...some content
</div>
</div>
Here is my CSS:
input + div {
background: #f0a;
display: none;
height: 200px;
width: 200px;
overflow-x: auto;
overflow-y: scroll;
}
input:focus + div {
display: block;
}
Current Behavior:
input
, I can see the div
.input
is gone, I can not see div
.div
, it hides.I dont want that behavior (When I try to click on div
, it hides).
I want a pure css solution if possible.
As I am using reactJS, I don't want to use jQuery.
div is focused
div
elements by default are not focusable. If you want to force them to be focusable add tabindex="0"
(see MDN: tabindex)
If you want the element to be focusable but not via keyboard navigation - then add tabindex="-1"
Now that the div
is focusable, we can use the :focus-within
pseudo class (caniuse) to check any element within the container div that is focused:
.wpr:focus-within div {
display: block;
}
Now we can also remove the CSS which check whether the input is focused.
input + div {
background: #f0a;
display: none;
height: 200px;
width: 200px;
overflow-x: auto;
overflow-y: scroll;
}
.wpr:focus-within div {
display: block;
}
<div class="wpr">
<input type="text" />
<div tabindex="-1">
...some content
</div>
</div>
Note: If browser compatibility is an issue (lack of IE/Edge support for :focus-within
) you could use @Temani Afif's solution as a fallback
input+div {
background: #f0a;
display: none;
height: 200px;
width: 200px;
overflow-x: auto;
overflow-y: scroll;
}
.wpr:focus-within div {
display: block;
}
input:focus + div {
display: block;
}
.wpr div:hover {
display: block;
}
<div class="wpr">
<input type="text" />
<div tabindex="-1">
...some content
</div>
</div>
You can add hover
style on the div to make it show so that when you click on it (when you hover on it) it won't hide even if you loose the focus :
input+div.select {
background: #f0a;
display: none;
height: 200px;
width: 200px;
overflow-x: auto;
overflow-y: scroll;
}
input:focus+div.select {
display: block;
}
div.select:hover {
display: block;
}
<div>
<input type="text" />
<div class="select">
...some content
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With