Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

I want to show a div only when:

  • input is focused.
  • div is focused.

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:

  • When Focus is on input, I can see the div.
  • When focus from input is gone, I can not see div.
  • When I try to click on 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.

like image 612
Vishal Avatar asked Dec 10 '17 08:12

Vishal


2 Answers

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>
like image 155
Danield Avatar answered Nov 28 '22 10:11

Danield


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>
like image 23
Temani Afif Avatar answered Nov 28 '22 09:11

Temani Afif