CSS3 selector :first-of-type with class name?

后端 未结 9 2001
梦毁少年i
梦毁少年i 2020-11-22 03:06

Is it possible to use the CSS3 selector :first-of-type to select the first element with a given class name? I haven\'t been successful with my test so I\'m thin

相关标签:
9条回答
  • 2020-11-22 03:41

    As a fallback solution, you could wrap your classes in a parent element like this:

    <div>
        <div>This text should appear as normal</div>
        <p>This text should be blue.</p>
        <div>
            <!-- first-child / first-of-type starts from here -->
            <p class="myclass1">This text should appear red.</p>
            <p class="myclass2">This text should appear green.</p>
        </div>
    </div>
    
    0 讨论(0)
  • 2020-11-22 03:48

    The draft CSS Selectors Level 4 proposes to add an of <other-selector> grammar within the :nth-child selector. This would allow you to pick out the nth child matching a given other selector:

    :nth-child(1 of p.myclass) 
    

    Previous drafts used a new pseudo-class, :nth-match(), so you may see that syntax in some discussions of the feature:

    :nth-match(1 of p.myclass)
    

    This has now been implemented in WebKit, and is thus available in Safari, but that appears to be the only browser that supports it. There are tickets filed for implementing it Blink (Chrome), Gecko (Firefox), and a request to implement it in Edge, but no apparent progress on any of these.

    0 讨论(0)
  • 2020-11-22 03:49

    This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.

    However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :

    :not(.myclass1) + .myclass1
    

    Full working code example:

    p:first-of-type {color:blue}
    p:not(.myclass1) + .myclass1 { color: red }
    p:not(.myclass2) + .myclass2 { color: green }
    <div>
      <div>This text should appear as normal</div>
      <p>This text should be blue.</p>
      <p class="myclass1">This text should appear red.</p>
      <p class="myclass2">This text should appear green.</p>
    </div>

    0 讨论(0)
提交回复
热议问题