集中在一个元素上,会改变其他元素的CSS。

huangapple go评论69阅读模式
英文:

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-withinMDN页面),它允许你为包含有焦点元素的父元素设置样式。

.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 -->

&lt;div class=&quot;search-box&quot;&gt;
    &lt;input type=&quot;text&quot; class=&quot;input-search&quot;&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月13日 18:41:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004488.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定