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

后端 未结 9 1999
梦毁少年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: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 }
    This text should appear as normal

    This text should be blue.

    This text should appear red.

    This text should appear green.

提交回复
热议问题