Vishal
Vishal

Reputation: 6368

hide a div when input or div is not focused using pure css

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:

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.

Upvotes: 5

Views: 2096

Answers (2)

Danield
Danield

Reputation: 125413

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>

Upvotes: 7

Temani Afif
Temani Afif

Reputation: 272590

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>

Upvotes: 2

Related Questions