Applying CSS to input container on focus

I have a div with a input field and a button inside. I would like the button to be hidden until the user focuses on the input.

I have tried to use the :focus pseudo-class on the containing div as I thought it would be inherited upon focusing on the input however it did not work.

Here is my html

<div class="search">
  <input type="text" placeholder="Search..." />
  <button type="submit">Search</button>
</div>

And here is the css I have already tried

.search button {
  display: none;
}

.search:focus button {
  display: block;
}

Is it possible to do this without JavaScript?


solution

In this case, you can use the adjacent sibling combinator, +.

Example Here

.search input:focus + button {
  display: block;
}

As FelipeAls points out, though, you can’t click on the button if the focus is removed. You could therefore do something like this in addition:

Example Here

.search button:hover, .search button:focus {
  display:block;
}