如何使用 CSS 选择器(如 :focus)修改同级的属性?
我的网站 http://ethoma.com/wp/ 上的某些代码遇到问题。在左侧的搜索栏中,我希望当搜索字段(其同级):焦点被触发时,通常为深灰色的“按 Enter 进行搜索”变为浅灰色。这是我当前拥有的代码:
#s
{
min-width:98%;
background-color:#2a2a2a;
color:#d3d3d3;
border:2px solid #000000;
font-size:.85 em;
height:1.9em;
display:inline !important;
border-radius:5px 5px 5px 5px;
}
#s:focus
{
border:2px solid #2a2a2a;
}
#searchsub
{
color:#2a2a2a;
text-align:right;
font-size:.65em;
font-weight:lighter;
}
#s:focus #searchsub
{
color:#cccccc;
}
好的,#s 是搜索字段,#searchsub 是我想要变成 #cccccc 的 div(浅灰色)。最后一组大括号似乎是我遇到问题的地方(不是大括号本身,而是它上面的选择器)。正如我所说,#s 是 #searchsub 的兄弟,反之亦然。
I am having trouble with some code on my site, http://ethoma.com/wp/. In the search bar, on the left side, I want the usually dark gray "hit enter to search" to turn a light gray when the search field (its sibling) :focus is triggered. Here is the code I currently have:
#s
{
min-width:98%;
background-color:#2a2a2a;
color:#d3d3d3;
border:2px solid #000000;
font-size:.85 em;
height:1.9em;
display:inline !important;
border-radius:5px 5px 5px 5px;
}
#s:focus
{
border:2px solid #2a2a2a;
}
#searchsub
{
color:#2a2a2a;
text-align:right;
font-size:.65em;
font-weight:lighter;
}
#s:focus #searchsub
{
color:#cccccc;
}
Okay, #s is the search field and #searchsub is the div that I want to turn #cccccc (light gray). The last set of curly braces seems to be where I am having the problem (not the braces themselves, but the selector above it). As I said #s is a sibling of #searchsub and vice versa.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像 stefmikhail 所说,选择器中的空格意味着
#searchsub
位于内部#s
。但就 HTML 而言,这显然是错误的,因为input
字段是空元素,并且其中不能包含其他元素。您想使用相邻的同级选择器
+
来代替,因为#searchsub
是#s
之后的同级选择器:Like stefmikhail said, the space in your selector means
#searchsub
is inside#s
. As far as HTML is concerned, though, that is obviously wrong becauseinput
fields are empty elements and you can't have other elements inside them.You want to use the adjacent sibling selector
+
instead, since#searchsub
is the sibling that comes after#s
:使用
相邻同级组合器
(仅当它紧跟在第一个元素之后)
通用同级组合器
(仅当它位于第一个元素之后(尽管不一定立即)
https:// /developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator
Use
adjacent sibling combinator
(only if it immediately follows the first element)
general sibling combinator
(only if it follows the first element (though not necessarily immediately)
https://developer.mozilla.org/en-US/docs/Web/CSS/General_sibling_combinator
您代码的问题在于,通过将
#searchsub
放置在#s:focus #searchsub
中的#s:focus
之后,您就是在告诉 CSS对 id#s
内的 id#searchsub
进行操作。我同意 JamWaffles 的观点,你可以用 javascript 来做到这一点。我会用 jQuery 来做,如果你愿意,我可以发布如何做。
The problem with your code is that by placing
#searchsub
after#s:focus
in#s:focus #searchsub
, you're telling CSS to act upon the id#searchsub
inside the id#s
.I agree with JamWaffles that you could do this with javascript. I would do it with jQuery, and if you would like, I can post how.