2

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?

0

1 Answer 1

7

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Perfect - thanks a lot. I will mark as answer in 13 minutes :)
Fine until you try to reach this button (edit: by tabbing)... then input hasn't focus anymore and the button gets back to its hidden state :(
@FelipeAls You are correct however this button will act as a fall-back for users with JavaScript disabled in this case, there will be another button which will override this when JavaScript is enabled so I am not too worried about it not being perfectly practical
The above works while click the button using mouse click.. but when i press the tab key the button disappears.. for that we can use the additional style.. .search button:focus { display:block; } ... so that while tabbing also the button becomes there..
@SoundarR Good point, I forgot about that :) Thanks for mentioning that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.