Is SnoopCode a good alternative for w3schools

CSS selector for the first element with class

CSS selection | CSS ID | CSS Class Picker - SelectorsHub demo to AUTOMATICALLY find CSS locators

I have a bunch of elements with a class name, but I can't seem to select the first element with the using the following CSS rule:

What is wrong with this selector and how do I fix it?

Thanks to the comments, I found out that the item has to be its parent's first child to be selected, which I don't. I have the following structure and this rule fails as mentioned in the comments:

How can I address the first child with a class? ?

  • For those confused about the different type of elements in my example (p, div), making them the same won't work either and the problem persists.
  • 4 I think so is the: First-Child-Selector should worked...
  • 33: First child would not be a very good name then. If you had a son and then a daughter, you wouldn't call your daughter your firstborn. Likewise, the first .home> .red is not the first child of .home, so it would be inappropriate to refer to it as such.
  • 1 No, this is how it should have worked: first-of-type
  • @EvanThompson Here's how does Job.

This is one of the most famous examples of writers misunderstanding how works. Introduced in CSS2, which represents pseudo-class the very first child of his parents. That's it. There is a very common misconception that it picks up any child that first meets the conditions given by the rest of the composite selector. Because of the way selectors work (an explanation can be found here), this just isn't the case.

Selectors Level 3 introduces a pseudo-class that represents the first element among siblings of its element type. This answer uses illustrations to explain the difference between and. As with It, no other conditions or attributes are considered. In HTML, the element type is represented by the tag name. That guy is in question.

Unfortunately, there is no similar pseudo-class to match the first child of a given class. One workaround that Lea Verou and I came up with for this (albeit completely independently) is to apply your desired styles first all Your elements with this class:

... then "undo" the styles for items with the class that come after the first oneusing the general sibling combiner in a superordinate rule:

Now only the first element with will have a limit.

Here is an illustration of how the rules are applied:

  1. No rules are applied. No border is rendered.
    This element has no class

  2. Only the first rule is applied. A red border is rendered.
    This element has the class, but no elements are prefixed with the class in its parent. This means that the second rule is not applied, only the first, and the element retains its edge.

  3. Both rules apply; No border is rendered.
    This element has the class. At least one other element is also prepended with the class. Thus, both rules are applied and the second one. The declaration overwrites the first and, so to speak, "undoes" it.

As a bonus, the general sibling combiner, although introduced in Selectors 3, is fairly well supported unlike IE7 and newer versions and which are only supported as of IE9. If you need good browser support, you're in luck.

Indeed, the fact that the sibling combiner is the only important component in this technique is and It has amazing browser support, so it's very versatile. You can customize it to filter items by other things besides class selectors:

  • You can use this to work around this in IE7 and IE8 by simply providing a type selector instead of a class selector (more on its incorrect use here in a later section):

  • You can filter by attribute selectors or other simple selectors instead of classes.

  • You can also combine this high-level technique with pseudo-elements, although technically pseudo-elements are not simple selectors.

Note that you need to know in advance what default styles will be used for your other sibling elements so that you can override the first rule. Since this involves overriding rules in CSS, you can't do the same thing with a single selector for use with Selenium's Selectors API or CSS locators.

It's worth noting that Selectors 4 is an extension of the notation (originally called an entirely new pseudoclass) that allows you to use something like instead of a hypothetical one. Since this is a relatively new proposal, there are not enough interoperable implementations to be used in production facilities. Hopefully that will change soon. In the meantime, the workaround I suggested should work for most of the cases.

Note that this answer assumes that the question looks for every first child that has a particular class. There is neither a pseudo-class nor a generic CSS solution for the nth match of a complex selector over the entire document Whether a solution exists depends heavily on the document structure. jQuery provides,, and more for this purpose, but again note that they work very differently than et al. With the Selectors API you can either use to get the very first match:

Or use with an indexer to select a specific match:


Although the solution in Philip Daubmeier's originally accepted answer (which was originally written by Martyn but has since been deleted) does not behave as you would expect.

For example, if you just want to select the ones in your original markup:

... then you can't use (equivalent) because each element is the first (and only) of its kind (and each), like that both is matched by the selector.

If the first element of a particular class is also the first of its kindthe pseudo-class will work, but This only happens by accident. This behavior is shown in Philip's answer. As soon as you insert an element of the same type in front of this element, the selection will fail. Take the updated markup:

Applying a rule with will work, but once you add another one without the class:

... the selector fails immediately because the first element is now that second Element.

  • 17 So is there a way to emulate? ? Select the last member of a class.
  • 1 @Rocket: Not that I can see :(
  • 4 Nice technology with the sibling. It might be worth noting that this also works with multiple sibling combiners, e.g. p ~ p ~ p selects the third element and beyond: jsfiddle.net/zpnnvedm/1
  • 2 @BoltClock Yes, sorry, I came here to find a solution and the OP-specific case wasn't that important to me. I actually can't understand why how does one work for a given type, I'm assuming the rule should be applied to every matching item, but it will only apply to the first match, even if there are 3 or more possible matches.
  • 3 According to caniuse the extension has already been implemented in Safari 9.1+. (I didn't check it though)

As the name suggests, the Selector is intended to select the first child of a parent tag. The children must be embedded in the same parent tag. Your exact example will work (just tried it here):

Maybe you've nested your tags in different parent tags? Are your class tags really the first few days with the parent?

Also note that this applies not just to the first such day in the entire document, but every time a new parent element is wrapped around it, such as

and then it will be red.

To update:

I don't know why Martyn deleted his answer, but he had the solution, the voters:

Thanks to Martyn. More information, for example here. Note that this is a CSS 3 selector. Therefore not all browsers (e.g. IE8 or older) recognize it.

  • It could have been my fault - as I'd pointed out to Martyn that a CSS3 selector liked suffering from the slight problem of not working at all in any current version of IE.
  • 26 I was a little confused when I read this. Strictly selects any element that is (a) the first child of its element type and (b) is of class "red". So if in the example the first

    did not have a "red" class, it would not be selected. Alternatively, if that and the first

    both had the class "red", both would be selected. jsfiddle.net/fvAxn

  • 7 @ Dan Mundy: is equivalent to, of course that is how it works. It can also fail the same way for the same reason I gave in my answer.
  • 4 @ David, I'm sure "Element / Tag" means when it says "Type". So only the element is taken into account, not things like classes.
  • 3 @gcampbell: Yes, that's exactly what it means, and that's why this answer is flawed. The reason the word "type" was chosen is to avoid coupling selectors with HTML / XML, as not all languages ​​have a concept of "tags" that define elements.

The correct answer is:

Part I: If the element is the first parent and has the class "red", it is given a border.
Part II: If the element ".red" is not the first element of its parent, but immediately follows an element without a class ".red", it also deserves the honor of this limit.

Violin or it didn't happen.

Philip Daubmeier's answer is accepted, but not correct - see attached violin.
BoltClock's answer would work, but unnecessarily defines styles and overrides them
(especially a problem where it would otherwise inherit a different limit - you don't want to declare any other limit: none)

EDIT: In the event that you have "red" after non-red multiple times, each "first" red gets the border. To prevent this from happening, one would have to use BoltClock's answer. See violin

  • 2 This answer is not wrong, the selector is Correct for the markup given, but I should reiterate that the situation mentioned in the edit is why I find an override is required, at least if you can't guarantee the markup structure - just because a follows a does it not always first among his siblings. And if the limit needs to be inherited, it's simply a matter of explanation instead of in the override rule.
  • 3 This solution is the best IMO as you can do the same for the last child as well.
  • @ A1rPun how do you change that for the last child?
  • @ Willem Just change to, but I see after testing that this doesn't always do the trick.
  • 4 I'm sorry, but it does not match "first child element with class .red", but rather "first element if it has class .red and the first .red element after a non .red element ". These two are not equivalent. Violin: jsfiddle.net/Vq8PB/166

You could use or

  • 6 It won't work unless you have one between that and your first item with class. Check out this JSFiddle.
  • 1 I have now seen that in the last example of his answer it reproduces the same behavior that I pointed out here. When I tried out your example and "played" a bit, I noticed this behavior and wanted to point it out so that future readers might become aware of it.

The above answers are too complex.

This will select the first class type. MDN source

  • 4 I can't find a reference to the first type, and the first type only applies to the tag name. Are you sure this answer is correct?
  • 1 was renamed to
  • 9 It doesn't work with classes. That's the way it is should work because choosing the nth of a class would be more useful than choosing the nth of a tag. But ': first-of-type' only worked with tagName so far. When it just so happens that "first-of-class" and "first-of-tag" refer to the same element, which they often do, it is easy to get confused that this is how it works. and then wonder what is broken when you come to a case where it doesn't.
  • 2 Not sure why this is not the selected answer. This does exactly what the OP asked for and works perfectly. SMH.
  • 1 @Bernesto, when you have a case where you have multiple elements of the same "type" let's say and some have the class. The selector selects the first instance of the "type" with the selected class, in this example the first and not the first instance of the class. The style is only implemented if this first instance of span also contains the class highlight. (codepen.io/andrewRmillar/pen/poJKJdJ)

To match your selector, the element must have the class name and must be the first child of its parent.

  • This is correct and this seems to be my problem. However, is there a way to select the first element with a class regardless of whether other elements are prepended?
  • If you looked at Martyn's answer, you didn't have to ask this :)

Since the other answers cover what not correct With that I will try the other half of how to fix it. Unfortunately, I don't know you have one CSS only at least here a solution not that I could think of it. But there are a few other options ...

  1. Assign a

    CSS:

    This CSS only matches elements both and classes.

  2. Alternatively, you can do the same thing in JavaScript. Example: jQuery you would do this with, using the same CSS as above:

  • Some time ago I developed a pure CSS solution. I've given it here as a canonical answer.
  • 1 As long as there is nothing comparable I would also suggest adding an additional class to the first element. Seems like the easiest solution for now.

I have this in my project.

According to your updated problem

how about

This will choose Class home, then the item Span and finally everything .red elements which are placed immediately after span elements.

Reference: http://www.w3schools.com/cssref/css_selectors.asp

I'm using CSS below to have a background image for the ul li list

You can use nth-of-type (1) but make sure the site doesn't have to support IE7 etc. If so, use jQuery to add a body class and find the element via IE7 body class, then element name and add it in nth child styling to it.

You can change your code into something like this to make it work

This does the job for you

Here is a CSS reference from SnoopCode on it.

For some reason, none of the above answers seemed to address the case of the real first and only first child of the parent.

All of the above answers fail if you only want to apply the style to the first grade child in this code.

  • 1 Your answer is essentially already in the top two answers to this question and does not add anything. Your use of the pseudo-class is also misleading because it is added before it does not change the way it works and only acts as a filter. If you've ever had a div then your selector wouldn't match because it's not the actual first child.
  • I don't think it's that easy for someone who needs the information. And yes, you are right about the case. This serves a more specific case. So I thought it might be useful.
  • That's exactly what I needed, precise and concise. Thank you @YavorIvanov

Try this simply and effectively

You could try something like this:

You can use this for the last element as well (if necessary):

All in all, after reading this and other pages and loads of documentation. Here is the summary:

  • For the first / last child: Now safe to use (supported by all modern browsers)
  • : nth-child () Safe to use now (supported by all modern browsers). But be careful, even siblings count! So the following does not work properly:

There is currently a selector: nth child (-n + 2 of .foo), which supports selection by class but is not supported by modern browsers, so not useful.

With that we have a Javascript solution (we will correct the example above):

I believe that using relative selector for selecting items to be placed immediately after works best here (as few suggested previously).

In this case this selector can also be used

However, this is the member selection, not class one.

Here you have a nice list of CSS selectors: https://kolosek.com/css-selectors/

I've just used it as a CSS selector successfully.

Try this solution:

CodePen link

  • 1 The question is "CSS selector for the first element with class", Not"CSS selector for the first element with tag name'.