elliott.david
2010-04-26 22:51
采纳率: 25%
浏览 1.4k

带 class 的第一个元素的 CSS 选择器

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?

</div>

转载于:https://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

18条回答 默认 最新

  • 三生石@ 2011-12-16 19:21
    已采纳

    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.

    打赏 评论
  • from.. 2010-04-26 22:58

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

    打赏 评论
  • ~Onlooker 2010-04-26 23:04

    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>
    
    打赏 评论
  • 叼花硬汉 2010-04-26 23:13

    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");
      
    打赏 评论
  • 北城已荒凉 2012-11-08 11:15

    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

    打赏 评论
  • 北城已荒凉 2013-06-03 12:59

    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.

    打赏 评论
  • 7*4 2014-01-21 11:49

    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

    打赏 评论
  • 三生石@ 2015-10-14 10:15

    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.

    打赏 评论
  • derek5. 2016-04-10 18:45

    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>
    
    打赏 评论
  • elliott.david 2016-07-26 08:19

    Try This Simple and Effective

     .home > span + .red{
          border:1px solid red;
        }
    
    打赏 评论
  • csdnceshi62 2016-08-04 22:06

    Try this :

        .class_name > *:first-child {
            border: 1px solid red;
        }
    
    打赏 评论
  • perhaps? 2016-11-02 21:29

    The above answers are too complex.

    .class:first-of-type { }
    

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

    打赏 评论
  • 撒拉嘿哟木头 2016-12-15 12:32

    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

    </div>
    
    打赏 评论
  • ~Onlooker 2017-01-13 00:57

    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>

    </div>
    
    打赏 评论
  • bug^君 2017-06-27 20:25

    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>

    </div>
    
    打赏 评论
  • 零零乙 2018-01-31 07:02

    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>

    </div>
    
    打赏 评论
  • 斗士狗 2018-04-11 06:47

    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/

    打赏 评论
  • 喵-见缝插针 2018-07-13 17:49

    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>

    </div>
    
    打赏 评论

相关推荐 更多相似问题