CSS selector for first element with class
Asked Answered
F

25

1327

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:

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

What is wrong in this selector and how do I correct it to target the first child with class red?

Fruitarian answered 26/4, 2010 at 22:51 Comment(1)
Check these references :link, linkPulchritude
U
1889

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. At the time this answer was first posted, the newly published FPWD of Selectors level 4 introduced an :nth-match() pseudo-class, designed around existing selector mechanics as I mentioned in the first paragraph by adding a selector-list argument, through which you can supply the rest of the compound selector to get the desired filtering behavior. In recent years this functionality was subsumed into :nth-child() itself, with the selector list appearing as an optional second argument, to simplify things as well as averting the false impression that :nth-match() matched across the entire document (see the final note below).

While we await cross-browser support (seriously, it's been nearly 10 years, and there has only been a single implementation for the last 5 of those years), one workaround that Lea Verou and I developed independently (she did it first!) 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:

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

.home > .red ~ .red {
    border: none;
}
<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 in the question 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.

On a final note, keep in mind that this answer assumes that the question is looking for any number of first child elements having 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 here:

<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 markup from the question:

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

Unhappy answered 16/12, 2011 at 19:21 Comment(9)
So, is there any way to emulate :last-of-class? Select the last element of a class.Purdah
I wonder why article > p ~ article > p doesn't work/produce the same effect as article > p ~ p.Fealty
@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/8135729Unhappy
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/1Chicoine
Really neat trick with the ~ operator, but why wouldn't the + operator be considered a simpler solution? span + p.redDestinee
@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.Unhappy
This only works if you have at least two of those items with class red applied. If you only have one it will still mark that first one with a red border; that is most likely not the behavior that people are looking for...Lodestar
@Wilt: I guess it depends on how often people find themselves working with only one element, but I'm surprised to hear that people most likely don't want the element highlighted if it's unique.Unhappy
It is now possible to do :nth-child(1 of .foo), and it is supported in over 92% of browsers.Lycia
A
400

The :first-child selector is intended, like the name says, to select the first child of a parent tag. So this example will work (Just tried it here):

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

This won't work, though, if you've nested your tags under different parent tags, or if your tags of class red aren't the first tags under the parent.

Notice also that this doesn't only apply to the first such tag in the whole document, but every time 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.

For your case, you can use the :nth-of-type selector:

.red:nth-of-type(1)
{
    border:5px 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>

Credits to Martyn, who deleted his answer containing this approach.

More information about :nth-child() and :nth-of-type() is available at http://www.quirksmode.org/css/nthchild.html.

Be aware that this is a CSS3 selector, therefore some now outdated browser versions may not behave as expected (e.g. IE8 or older). Visit https://caniuse.com/?search=nth-of-type for more details.

Aldrin answered 26/4, 2010 at 22:58 Comment(9)
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.Moiety
@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.Aldrin
:first-child - while not solving Rajat's problem - does in fact work in both IE7 and IE8.Moiety
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'); } :-)Moiety
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/fvAxnFregoso
What @Fregoso 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().Unhappy
@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.Unhappy
@Fregoso I'm sure :nth-of-type means "element/tag" when it says "type". So it only considers the element, not things like classes.Instrumentation
@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.Unhappy
A
102

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

Armes answered 8/11, 2012 at 11:15 Comment(1)
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.Unhappy
R
41

I am surprised no one mentioned the cleanest solution:

.red:not(.red ~ .red) {
    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>
Retrenchment answered 28/8, 2021 at 12:35 Comment(6)
A .red that is not a ".red preceded with a .red". Only the first one is in this example. But it won't work if another class is inserted in between. Note: .red:not(.red ~ *) should work too ("a red that is not "anything preceded with a .red")Boland
@Boland why won't it work ? Are you sure you are not mistaking '+' and '~' selectors, immediate sibling and any-distance sibling ?Pollard
How to select last element with 'red' class?Stotinka
Needs some explanation. Code-only answers are discouraged.Tynan
Great answer. Here is explanation: The element1~element2 selector matches occurrences of element2 that are preceded by element1. Both elements must have the same parent, but element2 does not have to be immediately preceded by element1.Houchens
It's still targeting all the elements with the given class on my WordPress Elementor page (which probably admittedly has some pretty mess CSS, but still, it anecdotally showcases that it's not foolproof)Extramarital
S
33

The above answers are too complex.

.class:first-of-type { }

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

Note: Tested with Chrome 91 and Firefox 89, June 2021.

Straka answered 2/11, 2016 at 21:29 Comment(4)
first-type has been renamed to first-of-typeStraka
It does not work with classes. That's how it should work, because selecting the nth of a class would be more useful than selecting the nth of a tag. But ':first-of-type' has only ever worked by tagName. If it just so happens that 'first-of-class' and 'first-of-tag' refer to the same element, which they often do, it's easy to confuse yourself into thinking it does work that way; and then wondering what's broken when you come to a case in which they don't.Erythroblast
@Bernesto, when you have a case where you have multiple elements of the same "type", lets say <span>, and a few have the class highlight. The .highlight:first-of-type selector will select the first instance of the "type" with the selected class, in this example the first <span>, and not the first instance of the class highlight. Only if that first instance of span also has the class highlight will the style be implemented. (codepen.io/andrewRmillar/pen/poJKJdJ)Yaya
The reason my answer is so complex is because its final section, as well as my comments on several of the other answers, explains precisely why this is flawed. Adding a link to MDN to your answer two years after the fact doesn't exactly do anything to support it when you haven't tried to relate the MDN material to it - presumably because you can't.Unhappy
N
26

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

.red {
  color: green;  
}

/* .red:nth-of-type(1) */
/* .red:first-of-type */
.home :nth-child(1 of .red) {
  color: red;  
}
<div class="home">
  <span>blah</span>
  <p>not red</p>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <p class="red">fourth</p>
</div>
Nellynelms answered 13/1, 2017 at 0:57 Comment(4)
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.Gassing
@FranciscoRomero using the :nth-child(1 of .red) will fix the issueNellynelms
At the time I wrote the comment, that selector did not exist. I did not even know about that property but I love it, it was really necessary. Thank you for share it. It does not have widely support yet, though.Gassing
nth-child(1 of .red) is fortunately widely supported as of Spring 2023 - see caniuse.Zettazeugma
C
11

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"></span> <!-- MATCH -->
</div>

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

<div>
    <span>Blah</span>
    <div><p class="red"></p></div> <!-- MATCH -->
</div>
Crowned answered 26/4, 2010 at 23:4 Comment(0)
W
10

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");
    
Wraf answered 26/4, 2010 at 23:13 Comment(2)
I came up with a CSS-only solution a while ago; I've reproduced it here as a canonical answer.Unhappy
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.Arsenopyrite
B
9

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>
Bulger answered 31/1, 2018 at 7:2 Comment(1)
You don't need :not(:first-child) when applying the technique in my answer. The ~ combinator implies that :not(:first-child) will always match and is therefore redundant - the only effect it really has on your selector is the extra specificity. And you don't need this extra specificity, so you can (and probably should) leave it out.Unhappy
T
6

With the latest nth-child of <selector> syntax, you can do this to achieve what you want.

Hope you like it.

.home :nth-child(1 of .red) {
    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>
Tenno answered 7/8, 2023 at 4:31 Comment(1)
Simple and elegant! Seems a lot easier than using the other more complicated options.Regiment
P
5

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>
Prehistoric answered 27/6, 2017 at 20:25 Comment(0)
E
4

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

Equipollent answered 21/1, 2014 at 11:49 Comment(0)
C
3

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>
Contessacontest answered 10/4, 2016 at 18:45 Comment(1)
The reason our answers didn't address this is because it's not what the question was asking to begin with. This answer would serve better as an answer to a separate question.Unhappy
H
3

The following code will definitely work well everywhere.
it is simple and short.

<div class="home">
    <span>blah</span>
    <p class="blue"> first-blue  </p>
    <p class="blue"> second-blue </p>
    <p class="blue"> third-blue  </p>

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

    <p class="pink"> first-pink  </p>
    <p class="pink"> second-pink </p>

    <p class="red">  new-first-red   </p>
    <p class="red">  new-second-red  </p>
</div>

we can select the first-red with:

.home .red:not(.home .red ~ .red) {
    background-color: blue;
}

if you want to select new-first-red too you should use + instead of ~.

Heir answered 18/7, 2022 at 2:58 Comment(1)
This should be the answer, because it really contains the filter for the one element in question, without having to change styles for anything else.Carlsbad
C
1

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.

Creepie answered 3/6, 2013 at 12:59 Comment(0)
S
1

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.

Standish answered 14/10, 2015 at 10:15 Comment(0)
C
0

All in All, after reading this all page and other ones and a lot of documentation. Here's the summary:

  • For first/last child: Safe to use now (Supported by all modern browsers)
  • :nth-child() Also safe to use now (Supported by all modern browsers). But be careful it even counts siblings! So, the following won't work properly:

/* This should select the first 2 element with class display_class
* but it will NOT WORK Because the nth-child count even siblings 
* including the first div skip_class
*/
.display_class:nth-child(-n+2){ 
    background-color:green; 
}
<ul>
   <li class="skip_class">test 1</li>
   <li class="display_class">test 2 should be in green</li>
   <li class="display_class">test 3 should be in green</li>
   <li class="display_class">test 4</li>
 </ul>

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

So, that leaves us with Javascript solution (we'll fix the example above):

// Here we'll go through the elements with the targeted class
// and add our classmodifer to only the first 2 elements!


[...document.querySelectorAll('.display_class')].forEach((element,index) => {
  if (index < 2) element.classList.add('display_class--green');
});
.display_class--green {
    background-color:green;
}
<ul>
   <li class="skip_class">test 1</li>
   <li class="display_class">test 2 should be in green</li>
   <li class="display_class">test 3 should be in green</li>
   <li class="display_class">test 4</li>
 </ul>
Columbuscolumbyne answered 21/10, 2020 at 23:29 Comment(0)
T
0

A quick 'n dirty jQuery solution for marking first and last element within a group of elements with the same classnames:

$('.my-selector').each(function(index, item) {
  if (!$(item).next().hasClass('my-selector')) {
    $(item).addClass('last');
  }
  if (!$(item).prev().hasClass('my-selector')) {
    $(item).addClass('first');
  }
});
.my-selector {
  padding: 5px;
  background: #ccc;
}

.my-selector.first {
  background: #fcc;
}

.my-selector.last {
  background: #cfc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
  <span>first element...</span>
  <div class="my-selector">Row 1</div>
  <div class="my-selector">Row 2</div>
  <div class="my-selector">Row 3</div>
  <div class="my-selector">Row 4</div>
  <span>other elements...</span>
  <div class="my-selector">Row 3</div>
  <div class="my-selector">Row 4</div>
</div>
Tarkington answered 10/10, 2022 at 13:56 Comment(0)
G
0

There is another way to make it work, if we look at the class as an attribute selection instead, the CSS Selector will allow first-of-type and last-of-type selectors.

.home > p[class="red"]:first-of-type {
    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>
Guelph answered 8/11, 2023 at 17:32 Comment(0)
C
-1

Try This Simple and Effective

 .home > span + .red{
      border:1px solid red;
    }
Courier answered 26/7, 2016 at 8:19 Comment(0)
S
-1

just use

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

it will work.

Shanty answered 18/4, 2022 at 21:54 Comment(2)
Instead of just saying use this or this will work explain how and why it will work.Botheration
Especially on an old question like this with tons of upvoted answersHarrow
P
-3

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/

Perish answered 11/4, 2018 at 6:47 Comment(0)
J
-3

Could you try something like this:

.red:first-of-type {
    border: 5px solid red;
}

you also can use this for last element (if you need it):

.red:last-of-type {
    border: 5px solid red;
}
Jeannettajeannette answered 18/9, 2020 at 7:6 Comment(0)
P
-4

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

Prandial answered 15/12, 2016 at 12:32 Comment(1)
The question is "CSS selector for first element with class", not "CSS selector for first element with tag name".Copyread
E
-6

I think a lot of people have explained already. your code is selecting only first child of the first instance. If you want to select all the first children of red class, you need to use

.home > .red:first-child {
    /* put your styling here */
}
Emmerie answered 16/2, 2021 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.