Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 369
Eric Thoma Avatar asked Aug 28 '11 23:08

Eric Thoma


People also ask

How do you target siblings in CSS?

General Sibling Selector (~) The general sibling selector selects all elements that are next siblings of a specified element.

How do you add focus in CSS?

The :focus CSS pseudo-class represents an element (such as a form input) that has received focus. It is generally triggered when the user clicks or taps on an element or selects it with the keyboard's Tab key.

How do I select siblings before CSS?

If you ever used CSS sibling selectors, you know there's only two. The + sibling combinator selects the first match that comes immediately after, and the ~ subsequent-sibling combinator matches all the ones that come after. But there's no way to select what came before.


2 Answers

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;
}
like image 127
BoltClock Avatar answered Oct 08 '22 01:10

BoltClock


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

like image 29
Jquestions Avatar answered Oct 07 '22 23:10

Jquestions