Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Focusing on one element, changes other element's CSS

Let’s have a look at this very simple code:

<div class="search-box">
    <input type="text" class="input-search">
</div>

What I’m trying to achieve?

When I’m in :focus on the .input-search, I want it to change the background-color of the whole .search-box

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I did try this but it seems to not work because I am probably selecting something wrong:

.input-search:focus{
    background-color: #fff;
}

However, I have no idea how to apply this same effect to the .search-box class.

Thanks for any help yall!

>Solution :

CSS cannot traverse up the DOM, so :focus can only be used for styling the specifically focused element. There is however :focus-within (MDN page) which will allow you to style a parent element containing a focused element.

.search-box:focus-within {
    background-color: #f00;
}
<div class="search-box">
    <input type="text" class="input-search">
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading