Sunday, 19 June 2016

CSS selector to select first element of a given class



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:




might have a different name
structure and element count might differ
our target

this shouldn't be affected
this shouldn't be affected




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 occurrence 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.


Answer



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:







Content

Content

Content

Content



Content

Content

Content

Content







  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.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...