CSS-Selector for multiple elements

2020-02-07 04:37发布

问题:

I am not at all getting how to use more advanced css-selectors like + or > But as I am now needing it to prevent too much JS, maybe someone can help me out with this particular situation of this block:

<section class="rf_re1-suche_container">
    <input type="search" placeholder="Your search">
    <button>Send</button>
</section>

and I wanna do that:

.rf_re1-suche_container input:focus{
    background:orange;
}

but also for the button. So: If the input has a focus I want the input AND the button to have the same background. How would I do that? Thanks!

回答1:

You will need to target the input and the button separately. Because you want this to apply only when the input has focus, you will need to repeat the entire selector including the input:focus portion, then use a + combinator to link the button to the focused input:

.rf_re1-suche_container input:focus,
.rf_re1-suche_container input:focus + button {
    background: orange;
}
<section class="rf_re1-suche_container">
    <input type="search" placeholder="Your search">
    <button>Send</button>
</section>



回答2:

Just add the selector for the button, separated with a comma:

.rf_re1-suche_container input:focus,
.rf_re1-suche_container input:focus ~ button {
    background: orange;
}

The tilde (~) is the general sibling selector. It selects the element ONLY if it is preceded by the element before the sibling.

This is by the way quite similar to the adjacent sibling selector, but with the latter the two elements need to be right behind eachother. In your case it doesn't really matter, as these two elements are the only one in the parent.