Mike Mike - 5 months ago 21
CSS Question

CSS solution to make drop-down element visible while focused

I'm trying to figure out if there is any pure CSS solution to keep a drop-down element open while the input field of that element is focused? Here is an example:



div {
width: 300px;
line-height: 50px;
text-align: center;
background: #e8e8e8;
border: 1px solid #666;
}

div:hover form {
display: block;
}

form {
display: none;
padding: 0 15px;
}

<div>Hover Me
<form class="search">
<input type="search" placeholder="What are you looking for?" autofocus>
<input type="button" value="Search!">
</form>
</div>





The idea is to keep the form visible when the search field is focused. Because when a user starts typing the search inquiry and the mouse move out of the hover zone, the form hides, and that's very annoying.

Side-question: Is it possible to focus via CSS search input element each time a
<div>
is hovered?

Answer

The solution has been already proposed, but lacks browser support:

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.

An element also matches :focus-within if one of its shadow-including descendants matches :focus.

div {
  width: 300px;
  line-height: 50px;
  text-align: center;
  background: #e8e8e8;
  border: 1px solid #666;
}
div:hover form, div:focus-within form {
  display: block;
}
form {
  display: none;
  padding: 0 15px;
}
<div tabindex="-1">Hover Me
  <form class="search">
    <input type="search" placeholder="What are you looking for?" autofocus>
    <input type="button" value="Search!">
  </form>
</div>

Meanwhile, you can use a polyfill:

div {
  width: 300px;
  line-height: 50px;
  text-align: center;
  background: #e8e8e8;
  border: 1px solid #666;
}
div:hover form, div.focus-within form {
  display: block;
}
form {
  display: none;
  padding: 0 15px;
}
<script src="https://gist.githubusercontent.com/aFarkas/a7e0d85450f323d5e164/raw/"></script>
<div tabindex="-1">Hover Me
  <form class="search">
    <input type="search" placeholder="What are you looking for?" autofocus>
    <input type="button" value="Search!">
  </form>
</div>