views:

26

answers:

1

Hello,

I'm trying to select a first element of class 'A' in an element with id or class 'B'. I've tried a combination of > + and first-child selectors, since it's not a first element inside class element 'B'. It worked, but ... i'm trying to override some default css and i have no control over the server side and it seems that the class 'A' element is sometimes generated in a different position. Here's an illustration:

<class C>
  <class B> might have a different name
      <some other classes> structure and element count might differ
      <class A></class A> our target
      <class A></class A> this shouldn't be affected
      <class A></class A> this shouldn't be affected
  </class B>
</class C>

Sometimes the name of the class 'B' differs and the elements before 'A' differ as well. So is there any way to select the first occurence of 'A' in an element 'C'? Because class 'C' is always there. I can't use + > and first-child selectors since the path to first 'A' element differs, but element 'C' is always there and it would be a nice starting point.

Thanks for the help

A: 

There's the :first-of-type pseudo-class, but it's a CSS3 selector and as such support for it is poor.

You could still give it a shot though. I'll see if I can find any more compatible CSS2.1 solutions in the meantime, and if I do I'll update my answer accordingly.

.C > * > .A:first-of-type {
    /* Style only first of class A which is a grandchild of class C */
}

For those curious what exactly the :first-of-type pseudo-class selects, an illustration:

<div class="C">
    <!--
    As in the question, this element may have a varying class.
    Hence the intermediate '*' selector above (I don't know what tag it is).
    -->
    <div class="B">
        <div class="E">Content</div> <!-- Not selected [1] -->
        <div class="F">Content</div> <!-- Not selected [1] -->
        <div class="A">Content</div> <!-- Selected [2] -->
        <div class="A">Content</div> <!-- Not selected [3] -->
    </div>
    <div class="D">
        <div class="A">Content</div> <!-- Selected [2] -->
        <div class="E">Content</div> <!-- Not selected [1] -->
        <div class="F">Content</div> <!-- Not selected [1] -->
        <div class="A">Content</div> <!-- Not selected [3] -->
    </div>
</div>

Footnotes:

  1. Not selected as it's not of class A at all.
  2. Selected as it's of class A and the first such element.
  3. Not selected as it's of class A but not the first such element.
BoltClock
Yep, already solved with this one. I guess clients will have to be happy with it, since there's no other way to do that except with javascript. it was enough to do "C table.A:first-of-type"
Marius S.
I hope too that they're fine with JavaScript. Happy designing!
BoltClock