英文:
Focusing on one element, changes other element's CSS
问题
当我在.input-search
上:focus时,我想要改变整个.search-box
的背景颜色。我尝试了以下代码,但似乎不起作用,可能是我选择的东西不对:
.input-search:focus {
background-color: #fff;
}
然而,我不知道如何将相同的效果应用到.search-box
类。感谢大家的帮助!
英文:
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
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!
答案1
得分: 1
CSS无法遍历DOM上的元素,所以:focus
只能用于为具体焦点的元素设置样式。不过,有:focus-within
(MDN页面),它允许你为包含有焦点元素的父元素设置样式。
.search-box:focus-within {
background-color: #f00;
}
<div class="search-box">
<input type="text" class="input-search">
</div>
英文:
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.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.search-box:focus-within {
background-color: #f00;
}
<!-- language: lang-html -->
<div class="search-box">
<input type="text" class="input-search">
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论