Wilf
Wilf

Reputation: 2315

How to apply color to all element between the first and the last without giving a number to nth-child()?

I need to know how to apply the color or background color to all elements between the first and the last element without adding number into nth-child().

Assume that I have a dynamic stack of p on a page. And I'd like them to be highlighted except both ends (for some reasons). Or make them a different color.

HTML

<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>
<p>child</p>

CSS

p {
    border:solid 1px #ccc;
}
p:first-child, p:last-child {
    background-color:yellow;
}
p:nth-child() {
    background-color:#eeeeeee;
}

To make it clearer. I also make a live version here : http://jsfiddle.net/nobuts/s95a1rue/2/

Is it possible to just use html and css (not jquery nor javascript)?

Upvotes: 2

Views: 274

Answers (3)

j08691
j08691

Reputation: 208040

You could use :not like:

p {
    border:solid 1px #ccc;
}
p:not(:first-child):not(:last-child) {
    background-color:yellow;
}

jsFiddle example

Upvotes: 7

Joey N
Joey N

Reputation: 368

The :first-child & :last-child tags take precedence. Applying a background to all rows and then specifying something different for first/last should work.

p{
 background-color:#aaaaaa;
 }

p:first-child, p:last-child{
 background-color:#ffffff;
 }

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382514

Just like this :

p {
    background-color:#eeeeee;
    border:solid 1px #ccc;
}
p:first-child, p:last-child {
    background-color:yellow;
}

The second selector has a higher specificity than the first one, that's why it works.

Note : be careful that #eeeeeee (7 e) isn't a valid color.

Upvotes: 6

Related Questions