Reputation: 2315
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
Reputation: 208040
You could use :not
like:
p {
border:solid 1px #ccc;
}
p:not(:first-child):not(:last-child) {
background-color:yellow;
}
Upvotes: 7
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
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