Can I write a CSS selector selecting elements NOT having a certain class or attribute?

前端 未结 10 616
不知归路
不知归路 2020-11-22 10:47

I would like to write a CSS selector rule that selects all elements that don\'t have a certain class. For example, given the following HTML:



        
10条回答
  •  悲&欢浪女
    2020-11-22 11:47

    Using the :not() pseudo class:

    For selecting everything but a certain element (or elements). We can use the :not() CSS pseudo class. The :not() pseudo class requires a CSS selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.

    Examples:

    /* This query selects All div elements except for   */
    div:not(.foo) {
      background-color: red;
    }
    
    
    /* Selects all hovered nav elements inside section element except
       for the nav elements which have the ID foo*/
    section nav:hover:not(#foo) {
      background-color: red;
    }
    
    
    /* selects all li elements inside an ul which are not odd */
    ul li:not(:nth-child(odd)) { 
      color: red;
    }
    test
    test


    • 1
    • 2
    • 3
    • 4
    • 5

    We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:

    /* This selector has a higher specificity than the #foo below */
    #foo:not(#bar) {
      color: red;
    }
    
    /* This selector is lower in the cascade but is overruled by the style above */
    #foo {
      color: green;
    }
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

提交回复
热议问题