CSS selector to select first element of a given class

CSS3 provides the :first-of-type pseudo-class for selecting the first element of its type in relation to its siblings. However it doesn’t have a :first-of-class pseudo-class.

As a workaround, if you know the default styles for your other .A elements, you can use an overriding rule with the general sibling combinator ~ to apply styles to them. This way, you sort of “undo” the first rule.

The bad news is that ~ is a CSS3 selector.
The good news is that IE recognizes it starting from IE7, like CSS2’s >, so if you’re worried about browser compatibility, the only “major browser” this fails on is IE6.

So you have these two rules:

.C > * > .A {
    /* 
     * Style every .A that's a grandchild of .C.
     * This is the element you're looking for.
     */
}

.C > * > .A ~ .A {
    /* 
     * Style only the .A elements following the first .A child
     * of each element that's a child of .C.
     * You need to manually revert/undo the styles in the above rule here.
     */
}

How styles are applied to elements is illustrated below:

<div class="C">
    <!--
    As in the question, this element may have a class other than B.
    Hence the intermediate '*' selector above (I don't know what tag it is).
    -->
    <div class="B">
        <div class="E">Content</div> <!-- [1] -->
        <div class="F">Content</div> <!-- [1] -->
        <div class="A">Content</div> <!-- [2] -->
        <div class="A">Content</div> <!-- [3] -->
    </div>
    <div class="D">
        <div class="A">Content</div> <!-- [2] -->
        <div class="E">Content</div> <!-- [1] -->
        <div class="F">Content</div> <!-- [1] -->
        <div class="A">Content</div> <!-- [3] -->
    </div>
</div>
  1. This element does not have class A. No rules are applied.

  2. This element has class A, so the first rule is applied. However it doesn’t have any other such elements occurring before it, which the ~ selector requires, so the second rule is not applied.

  3. This element has class A, so the first rule is applied. It also comes after other elements with the same class under the same parent, as required by ~, so the second rule is also applied. The first rule is overridden.

Leave a Comment