How do I modify properties of siblings with CSS selectors like :focus?

依然范特西╮ 提交于 2019-12-22 03:59:11

问题


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.


回答1:


Like stefmikhail said, the space in your selector means #searchsub is inside #s. As far as HTML is concerned, though, that is obviously wrong because input 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:

#s:focus + #searchsub
{
    color:#cccccc;
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/7224751/how-do-i-modify-properties-of-siblings-with-css-selectors-like-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!