Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the direct first element after another element in CSS [duplicate]

Tags:

html

css

I have the following HTML:

<div id="form">
    <form>
       <textarea id="text"></textarea>
       <span class="error">select this</span>
       <span class="error">don't select this</span>
    </form>
</div>

In CSS, how can I select only the first span element directly after the textarea element and not select the other span elements after the first?

like image 619
Carven Avatar asked Dec 15 '22 23:12

Carven


2 Answers

You can use an adjacent sibling combinator:

#text + span {
    /* Styles */
}

Here's a working example.

Update (see comments)

To target the second span you can simply add another adjacent sibling combinator to the selector:

#text + span + span {
    /* Styles */
}
like image 112
James Allardice Avatar answered Apr 28 '23 09:04

James Allardice


Use the + (adjacent sibling) selector:

textarea + span { ... }

Demo: http://jsfiddle.net/ThiefMaster/ngrZz/

like image 32
ThiefMaster Avatar answered Apr 28 '23 09:04

ThiefMaster