Reputation: 1501
we have a partial html:
<ul>
<li class="class1">AFFECTED</li>
<li class="class1 class2">NOT</li>
<li class="class1">NOT</li>
</ul>
<ul>
<li class="class1 class2">NOT</li>
<li class="class1">AFFECTED</li>
<li class="class1">NOT</li>
</ul>
<ul>
<li>NOT</li>
<li class="class1">AFFECTED</li>
<li class="class1">NOT</li>
</ul>
I need a universal css-selector for the first li's of any list with only class1.
I've tried to use :not(class2), [class2] :first-child & :first-of-type but with no avail.
Thanks!
Solution: http://jsfiddle.net/6hxZa/3/
Upvotes: 2
Views: 16567
Reputation: 723448
You should be able to capture only the elements with .class1
and no other using this selector:
li[class="class1"]
You won't be able to match only the first out of these elements because there isn't a selector to do that. :first-child
only selects the very first child within the ul
regardless of what classes it has, and :first-of-type
selects the first li
, also regardless of its classes (effectively making it the same as :first-child
for li
elements). You'll have to use the technique given here (where it also explains why these two pseudo-classes don't work) to apply the rule to all such elements then undo it for subsequent ones:
li[class="class1"] {
/* Apply styles... */
}
li[class="class1"] ~ li[class="class1"] {
/* ... and remove them after the first */
}
Note that the same selector is used so both classless elements and elements with .class2
are completely unaffected.
This jsFiddle demonstrates the desired effect with the provided HTML: http://jsfiddle.net/Cmypc/4/
Upvotes: 12
Reputation: 7939
If you want to specifically exclude class2
from the selector, use:
li.class1:first-child:not(.class2) { }
If you want to exclude any additional classes other than class1
use:
li[class=class1]:first-child { }
I would recommend the first if you know which class(es) you're excluding as it will interfere less with other/future styles.
jsFiddle of #1: http://jsfiddle.net/Cmypc/ jsFiddle of #2: http://jsfiddle.net/Cmypc/1/
EDIT If you're looking for a :first-of-class
selector, there isn't one (see this thread). A future solution may be the :nth-match
selector but you'll have to wait for CSS4. Alternatively, you can use a more elaborate clearing selector to undo the styles applied (see BoltClock's answer) as a workaround.
Upvotes: 5