JazzyP
JazzyP

Reputation: 948

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?

Upvotes: 2

Views: 2308

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241198

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;
}

Upvotes: 7

Related Questions