By Rajat


2010-04-26 22:51:13 8 Comments

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

.red:first-child {
    border: 5px solid red;
}
<p class="red"></p>
<div class="red"></div>

What is wrong in this selector and how do I correct it?

Thanks to the comments, I figured out that the element has to be the first child of its parent to get selected which is not the case that I have. I have the following structure, and this rule fails as mentioned in the comments:

.home .red:first-child {
    border: 1px solid red;
}
<div class="home">
    <span>blah</span>
    <p class="red">first</p>
    <p class="red">second</p>
    <p class="red">third</p>
    <p class="red">fourth</p>
</div>

How can I target the first child with class red?

18 comments

@Alexander V. Ulyanov 2018-07-13 17:49:12

Needed only first and only one paragraph make red. How?

<!DOCTYPE html><html><head><style>

article p:nth-child(1){background: red}
article p:first-child{background: red}

</style></head><body>

<p style="color:blue">Needed only first and only one paragraph had red. How?</p>

<article>
<p>The first paragraph.</p>
<div><p>The second paragraph.</p></div>
<p>The third paragraph.</p>
<div><p>The fourth paragraph.</p></div>
</article>

</body></html>

@Gabriel Fair 2016-11-02 21:29:04

The above answers are too complex.

.class:first-of-type { }

This will select the first-type of class. MDN Source

@Matt Broatch 2017-10-10 18:58:58

I can't find any reference to first-type, and first-of-type only applies to tag name; are you sure this answer is correct?

@evolutionxbox 2018-02-08 09:28:13

@Gabriel Fair 2018-06-28 13:54:43

first-type has been renamed to first-of-type

@li bing zhao 2017-06-27 20:25:29

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

#footer .module:nth-of-type(1)>.menu>li:nth-of-type(1){
  background-position: center;
  background-image: url(http://monagentvoyagessuperprix.j3.voyagesendirect.com/images/stories/images_monagentvoyagessuperprix/layout/icon-home.png);
  background-repeat: no-repeat;
}
<footer id="footer">
  <div class="module">
    <ul class="menu ">
      <li class="level1 item308 active current"></li>
      <li> </li>
    </ul> 
  </div>
  <div class="module">
    <ul class="menu "><li></li>
      <li></li> 
    </ul>
  </div>
  <div class="module">
    <ul class="menu ">
      <li></li>
      <li></li>
    </ul>
  </div>
</footer>

@Yavor Ivanov 2016-04-10 18:45:58

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

#element_id > .class_name:first-child

All the above answers will fail if you want to apply the style to only the first class child within this code.

<aside id="element_id">
  Content
  <div class="class_name">First content that need to be styled</div>
  <div class="class_name">
    Second content that don't need to be styled
    <div>
      <div>
        <div class="class_name">deep content - no style</div>
        <div class="class_name">deep content - no style</div>
        <div>
          <div class="class_name">deep content - no style</div>
        </div>
      </div>
    </div>
  </div>
</aside>

@j08691 2016-04-10 19:21:03

Your answer is essentially already contained in the top two highest answers to this question and adds nothing. Also, your use of the :first-child pseudo-class is misleading since it adding .class_name before it doesn't change the way it work and merely makes it act as a filter. If you have a div before <div class="class_name">First content that need to be styled</div> then your selector wouldn't match since it's not the actual first child.

@Yavor Ivanov 2016-04-11 14:12:55

I don't think it's that straight forward for someone who needs the info. And yes you are right about the case. This serves a more specific case. This is why I thought it might be useful.

@quantme 2018-06-18 22:49:27

This is exactly what I needed, precise and concise. Thank you @YavorIvanov

@Santosh Khalse 2016-12-15 12:32:53

Try this solution:

 .home p:first-of-type {
  border:5px solid red;
  width:100%;
  display:block;
}
<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

CodePen link

@evolutionxbox 2018-02-08 09:28:40

This only works if the first item is not a div.

@Nesha Zoric 2018-04-11 06:47:01

I believe that using relative selector + for selecting elements placed immediately after, works here the best (as few suggested before).

It is also possible for this case to use this selector

.home p:first-of-type

but this is element selector not the class one.

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

@Yener Örer 2018-01-31 07:02:47

I got this one in my project.

div > .b ~ .b:not(:first-child) {
	background: none;
}
div > .b {
    background: red;
}
<div>
      <p class="a">The first paragraph.</p>
      <p class="a">The second paragraph.</p>
      <p class="b">The third paragraph.</p>
      <p class="b">The fourth paragraph.</p>
  </div>

@BoltClock 2011-12-16 19:21:56

This is one of the most well-known examples of authors misunderstanding how :first-child works. Introduced in CSS2, the :first-child pseudo-class represents the very first child of its parent. That's it. There's a very common misconception that it picks up whichever child element is the first to match the conditions specified by the rest of the compound selector. Due to the way selectors work (see here for an explanation), that is simply not true.

Selectors level 3 introduces a :first-of-type pseudo-class, which represents the first element among siblings of its element type. This answer explains, with illustrations, the difference between :first-child and :first-of-type. However, as with :first-child, it does not look at any other conditions or attributes. In HTML, the element type is represented by the tag name. In the question, that type is p.

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

/* 
 * Select all .red children of .home, including the first one,
 * and give them a border.
 */
.home > .red {
    border: 1px solid red;
}

... then "undo" the styles for elements with the class that come after the first one, using the general sibling combinator ~ in an overriding rule:

/* 
 * Select all but the first .red child of .home,
 * and remove the border from the previous rule.
 */
.home > .red ~ .red {
    border: none;
}

Now only the first element with class="red" will have a border.

Here's an illustration of how the rules are applied:

<div class="home">
  <span>blah</span>         <!-- [1] -->
  <p class="red">first</p>  <!-- [2] -->
  <p class="red">second</p> <!-- [3] -->
  <p class="red">third</p>  <!-- [3] -->
  <p class="red">fourth</p> <!-- [3] -->
</div>
  1. No rules are applied; no border is rendered.
    This element does not have the class red, so it's skipped.

  2. Only the first rule is applied; a red border is rendered.
    This element has the class red, but it's not preceded by any elements with the class red in its parent. Thus the second rule is not applied, only the first, and the element keeps its border.

  3. Both rules are applied; no border is rendered.
    This element has the class red. It is also preceded by at least one other element with the class red. Thus both rules are applied, and the second border declaration overrides the first, thereby "undoing" it, so to speak.

As a bonus, although it was introduced in Selectors 3, the general sibling combinator is actually pretty well-supported by IE7 and newer, unlike :first-of-type and :nth-of-type() which are only supported by IE9 onward. If you need good browser support, you're in luck.

In fact, the fact that the sibling combinator is the only important component in this technique, and it has such amazing browser support, makes this technique very versatile — you can adapt it for filtering elements by other things, besides class selectors:

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

    article > p {
        /* Apply styles to article > p:first-of-type, which may or may not be :first-child */
    }
    
    article > p ~ p {
        /* Undo the above styles for every subsequent article > p */
    }
    
  • You can filter by attribute selectors or any other simple selectors instead of classes.

  • You can also combine this overriding technique with pseudo-elements even though pseudo-elements technically aren't simple selectors.

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

It's worth mentioning that Selectors 4 introduces an extension to the :nth-child() notation (originally an entirely new pseudo-class called :nth-match()), which will allow you to use something like :nth-child(1 of .red) in lieu of a hypothetical .red:first-of-class. Being a relatively recent proposal, there aren't enough interoperable implementations for it to be usable in production sites yet. Hopefully this will change soon. In the meantime, the workaround I've suggested should work for most cases.

Keep in mind that this answer assumes that the question is looking for every first child element that has a given class. There is neither a pseudo-class nor even a generic CSS solution for the nth match of a complex selector across the entire document — whether a solution exists depends heavily on the document structure. jQuery provides :eq(), :first, :last and more for this purpose, but note again that they function very differently from :nth-child() et al. Using the Selectors API, you can either use document.querySelector() to obtain the very first match:

var first = document.querySelector('.home > .red');

Or use document.querySelectorAll() with an indexer to pick any specific match:

var redElements = document.querySelectorAll('.home > .red');
var first = redElements[0];
var second = redElements[1];
// etc

Although the .red:nth-of-type(1) solution in the original accepted answer by Philip Daubmeier works (which was originally written by Martyn but deleted since), it does not behave the way you'd expect it to.

For example, if you only wanted to select the p in your original markup:

<p class="red"></p>
<div class="red"></div>

... then you can't use .red:first-of-type (equivalent to .red:nth-of-type(1)), because each element is the first (and only) one of its type (p and div respectively), so both will be matched by the selector.

When the first element of a certain class is also the first of its type, the pseudo-class will work, but this happens only by coincidence. This behavior is demonstrated in Philip's answer. The moment you stick in an element of the same type before this element, the selector will fail. Taking the updated markup:

<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

Applying a rule with .red:first-of-type will work, but once you add another p without the class:

<div class="home">
  <span>blah</span>
  <p>dummy</p>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

... the selector will immediately fail, because the first .red element is now the second p element.

@Rocket Hazmat 2012-05-04 22:08:41

So, is there any way to emulate :last-of-class? Select the last element of a class.

@BoltClock 2012-05-05 04:57:27

@Rocket: Not that I can see :(

@LazerSharks 2014-08-29 23:55:48

I wonder why article > p ~ article > p doesn't work/produce the same effect as article > p ~ p.

@BoltClock 2014-08-30 04:01:15

@Gnuey: That's because combinators are linear. It's a little hard to explain in a comment, but basically I'd say the first > p implies that the second p is a child of the same article by way of the sibling combinator, so replacing that second p with article works similarly, and the following > p traverses one additional level down from that point. I have a couple of other answers that explain it in much greater detail: stackoverflow.com/a/3851754 stackoverflow.com/a/8135729

@Legolas 2015-04-15 13:53:18

Nice technique with the sibling. It might be worth noting this works with multiple sibling combinators as well, e.g. p~p~p will select the third item and beyond: jsfiddle.net/zpnnvedm/1

@Gerard Reches 2016-06-07 17:36:24

Thanks to share this workaround. But why to apply the styles to all the selected elements and then overwrite them with the general sibling selector instead of only apply the styles directly with the general sibling selector? Is that necessary?

@BoltClock 2016-06-08 05:17:07

@Gerard Reches: Was my illustration + explanations not clear enough?

@Gerard Reches 2016-06-08 13:08:14

@BoltClock Yes, sorry, I came here for a solution and I didn't care so much about the OP specific case. I actually can't understand why the general sibling selector ~ works like a :not(:first-of-*) for a specific type, I assume that it should apply the rule to each matching element, but it is applied only for the first match even when there are 3 or more possible matches.

@Danield 2016-09-14 06:25:07

According to caniuse the :nth-child(1 of .foo) extension has already been implemented on Safari 9.1+ . (I haven't checked though)

@BoltClock 2016-09-14 06:57:49

@Danield: Yes, it has. Safari 9 shipped with a number of selectors-4 features. See also stackoverflow.com/questions/35993727/…

@ElRoBe 2019-03-05 16:48:28

Really neat trick with the ~ operator, but why wouldn't the + operator be considered a simpler solution? span + p.red

@BoltClock 2019-03-05 16:50:17

@ElRoBe: That requires making the assumption that the first p.red will always directly follow a span. Sometimes, you may find yourself unable to make assumptions about the markup because it can vary in certain ways. For example, that span may not always be there, the first p.red may not directly follow it, or there may be more than one span + p.red pair in the same parent and you only want the very first to be affected. But if you are able to make these assumptions or even guarantees about the markup, then these simpler solutions will be available to you.

@ElRoBe 2019-03-06 17:08:20

Makes sense, just wanted to confirm that iff you can safely assume the order and presence of the elements, that the + operator would be a much simpler alternative (and can deal with more complex selectors, e.g. div > span + div > p > span.red or something).

@Moes 2017-01-13 00:57:44

you could use first-of-type or nth-of-type(1)

.red {
  color: green;  
}

/* .red:nth-of-type(1) */
.red:first-of-type {
  color: red;  
}
<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

@Francisco Romero 2017-11-21 14:48:15

It will not work if you have a <p></p> between the span and your first p element with red class. Look at this JSFiddle.

@Moes 2017-11-21 23:44:00

@Francisco Romero 2017-11-22 08:29:52

I saw now that it reproduces in the last example of his answer the same behaviour that I pointed here. When I tried your example and "played" a bit, I notice that behaviour and I wanted to point so future readers will be aware of.

@SamGoody 2012-11-08 11:15:25

The correct answer is:

.red:first-child, :not(.red) + .red { border:5px solid red }

Part I: If element is first to its parent and has class "red", it shall get border.
Part II: If ".red" element is not first to its parent, but is immediately following an element without class ".red", it shall also deserve the honor of said border.

Fiddle or it didn't happen.

Philip Daubmeier's answer, while accepted, is not correct - see attached fiddle.
BoltClock's answer would work, but unnecessarily defines and overwrites styles
(particularly an issue where it otherwise would inherit a different border - you don't want to declare other to border:none)

EDIT: In the event that you have "red" following non-red several times, each "first" red will get the border. To prevent that, one would need to use BoltClock's answer. See fiddle

@BoltClock 2013-02-26 17:08:14

This answer is not wrong, the selector is correct for the given markup, but I should reiterate that the situation mentioned in the edit is the reason why I state that an override is necessary at least when you cannot guarantee the markup structure - just because a .red follows a :not(.red) doesn't always make it the first .red among its siblings. And if the border needs to be inherited, it's simply a matter of declaring border: inherit instead of border: none in the override rule.

@A1rPun 2014-06-18 14:24:41

This solution is the best IMO because you can easily do the same for last-child.

@Willem 2014-09-27 02:12:56

@A1rPun How do you change this for last-child?

@A1rPun 2014-09-29 08:19:36

@Willem Just change first-child to last-child, but I see after testing that this doesn't always does the trick.

@SamGoody 2014-09-29 09:15:41

@Willem Don't forget that in CSS, first/last-child doesn't mean the last one that matches, it means the last element period, and only when the last element is the type described. Once you have allowed for that, last-child is all you need. Can you give a fiddle where you are having an issue?

@Willem 2014-09-30 09:52:11

@SamGoody I've realised it wasn't possible to do the particular use case I wanted. This method works because the DOM is traversed from top to bottom. There is no way to match an element depending on its next sibling due to the nature of + and ~.

@Gunchars 2015-05-04 20:39:03

I'm sorry, but it doesn't match "first child element that has class .red", instead it matches "first element if it has class .red and first .red element after a non .red element". These two are not equivalent. Fiddle: jsfiddle.net/Vq8PB/166

@Aaron Williams 2018-02-16 03:20:17

Glad I don't have to maintain your crappy code. Don't make things unnecessarily 'smart'

@Loy 2016-08-04 22:06:52

Try this :

    .class_name > *:first-child {
        border: 1px solid red;
    }

@Friend 2016-07-26 08:19:19

Try This Simple and Effective

 .home > span + .red{
      border:1px solid red;
    }

@Prabhakar 2015-10-14 10:15:28

You can change your code to something like this to get it work

<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

This does the job for you

.home span + .red{
      border:3px solid green;
    }

Here is a CSS reference from SnoopCode about that.

@StinkyCat 2014-01-21 11:49:39

According to your updated problem

<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>

how about

.home span + .red{
      border:1px solid red;
    }

This will select class home, then the element span and finally all .red elements that are placed immediately after span elements.

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

@Jamie Paterson 2013-06-03 12:59:17

You could use nth-of-type(1) but be sure that site doesn't need to support IE7 etc, if this is the case use jQuery to add body class then find element via IE7 body class then the element name, then add in the nth-child styling to it.

@Nick Craver 2010-04-26 23:13:51

Since the other answers cover what's wrong with it, I'll try the other half, how to fix it. Unfortunately, I don't know that you have a CSS only solution here, at least not that I can think of. There are some other options though....

  1. Assign a first class to the element when you generate it, like this:

    <p class="red first"></p>
    <div class="red"></div>
    

    CSS:

    .first.red {
      border:5px solid red;
    }
    

    This CSS only matches elements with both first and red classes.

  2. Alternatively, do the same in JavaScript, for example here's what jQuery you would use to do this, using the same CSS as above:

    $(".red:first").addClass("first");
    

@BoltClock 2011-12-16 19:22:57

I came up with a CSS-only solution a while ago; I've reproduced it here as a canonical answer.

@Kai Noack 2017-09-26 12:00:13

As long as there is nothing like :first-of-class, I would also suggest to add an extra class to the first element. Seems the easiest solution for now.

@Philip Daubmeier 2010-04-26 22:58:02

The :first-child selector is intended, like the name says, to select the first child of a parent tag. The children have to be embedded in the same parent tag. Your exact example will work (Just tried it here):

<body>
    <p class="red">first</p>
    <div class="red">second</div>
</body>

Maybe you have nested your tags in different parent tags? Are your tags of class red really the first tags under the parent?

Notice also that this doesnt only apply to the first such tag in the whole document, but everytime a new parent is wrapped around it, like:

<div>
    <p class="red">first</p>
    <div class="red">second</div>
</div>
<div>
    <p class="red">third</p>
    <div class="red">fourth</div>
</div>

first and third will be red then.

Update:

I dont know why martyn deleted his answer, but he had the solution, the :nth-of-type selector:

<html>
<head>
<style type="text/css">
.red:nth-of-type(1)
{
    border:5px solid red;
} 
</style>
</head>

<body>
    <div class="home">
        <span>blah</span>
        <p class="red">first</p>
        <p class="red">second</p>
        <p class="red">third</p>
        <p class="red">fourth</p>
    </div>
</body>
</html>

Credits to Martyn. More infos for example here. Be aware that this is a CSS 3 selector, therefore not all browsers will recognize it (e.g. IE8 or older).

@Már Örlygsson 2010-04-26 23:23:17

It might have been my fault - as I'd pointed out to Martyn that a CSS3 selector like :nth-of-type suffer the slight problem of not working at all in any current version of IE.

@Rajat 2010-04-26 23:24:15

the nth-of-type rule is the right fix. thanks

@Philip Daubmeier 2010-04-26 23:24:28

@Már Örlygsson: Oh I see. But that may be even the case with the first-child selector... And even if it works with the current IE, it doesnt mean it works with older ones, that are still used by many people.

@Már Örlygsson 2010-04-26 23:25:26

:first-child - while not solving Rajat's problem - does in fact work in both IE7 and IE8.

@Philip Daubmeier 2010-04-26 23:27:00

@Már Örlygsson: Really? That surprises me :) But then there are still IE6 users out there. You see you cant please everyone... :)

@Rajat 2010-04-26 23:29:14

I know it doesn't work in IE coz its CSS3 but i wanted to understand why it wasn't working for me. was just playing around :)

@Már Örlygsson 2010-04-26 23:31:42

To hack one's way towards IE support, one might consider (if only during a brief flash of utter madness) experiment using expression() syntax. Something along the lines of this untested pile of crazy: .red { behaviour: expression(window.firstRed||(this.style.border='5px solid red');window.firstRed=true;this.runtimeStyle.behaviour='none‌​'); } :-)

@David 2011-10-12 22:51:14

I got a bit confused reading this. Strictly .red:nth-of-type(1) will select any element which (a) is the first child of its element type, and (b) has the class "red". So if, in the example, the the first <p> did not have class "red", it would not be selected. Alternatively if the <span> and the first <p> both had class "red", they'd both be selected. jsfiddle.net/fvAxn

@BoltClock 2011-12-16 19:32:01

What @David said a couple months back is correct; :nth-of-type() is not a good solution to this. I have provided an alternative answer that should be more reliable and, as a bonus, works in IE7+, unlike :nth-of-type().

@Elle Mundy 2012-11-09 20:03:58

:first-of-type works, too.

@BoltClock 2013-02-13 20:19:48

@Dan Mundy: :first-of-type is equivalent to :nth-of-type(1), so of course it works, too. It can also fail, too, in the same way for the same reason stated in my answer.

@oriadam 2016-05-02 01:01:55

I tried using :not to select only the first (I can't use the "undo" trick because I use querySelectorAll). This .red:not(.red~.red) doesn't work. Any ideas anyone? jsfiddle.net/oriadam/27cfmbpp

@gcampbell 2016-06-29 17:42:55

@David I'm sure :nth-of-type means "element/tag" when it says "type". So it only considers the element, not things like classes.

@BoltClock 2017-07-06 03:29:25

@gcampbell: Yes, that's exactly what it means, and it's why this answer is flawed. The reason the word "type" was chosen is so as not to couple Selectors with HTML/XML, since not all languages have a concept of "tags" that define elements.

@Chetan Sastry 2010-04-26 23:04:16

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

<div>
    <span class="red"> <!-- MATCH -->
</div>

<div>
    <span>Blah</span>
    <p class="red"> <!-- NO MATCH -->
</div>

<div>
    <span>Blah</span>
    <div><p class="red"></div> <!-- MATCH -->
</div>

@Rajat 2010-04-26 23:12:24

this is correct and this seems to be my problem but is there a way to select the first element with a class irrespective of whether its preceeded by other elements ?

@Philip Daubmeier 2010-04-26 23:14:35

If you had looked at Martyns answer you had not have to ask this :)

Related Questions

Sponsored Content

27 Answered Questions

[SOLVED] Is there a CSS parent selector?

  • 2009-06-18 19:59:36
  • jcuenod
  • 1621066 View
  • 2744 Score
  • 27 Answer
  • Tags:   css css-selectors

19 Answered Questions

[SOLVED] Is it possible to apply CSS to half of a character?

13 Answered Questions

[SOLVED] Is there a "previous sibling" CSS selector?

  • 2009-11-30 04:06:36
  • Jourkey
  • 537919 View
  • 1156 Score
  • 13 Answer
  • Tags:   css css-selectors

11 Answered Questions

33 Answered Questions

[SOLVED] Change an HTML5 input's placeholder color with CSS

8 Answered Questions

[SOLVED] Which characters are valid in CSS class names/selectors?

  • 2009-01-15 23:37:39
  • Darryl Hein
  • 349498 View
  • 1124 Score
  • 8 Answer
  • Tags:   css css-selectors

9 Answered Questions

[SOLVED] Can I write a CSS selector selecting elements NOT having a certain class?

26 Answered Questions

[SOLVED] Set cellpadding and cellspacing in CSS?

3 Answered Questions

[SOLVED] Why do browsers match CSS selectors from right to left?

5 Answered Questions

[SOLVED] Is there a CSS selector for the first direct child only?

Sponsored Content