CSS Selector to Select Elements Not Having Certain Class / Attribute / Type

Use-Cases of this tutorial

  • Know how to select elements with CSS that don't satisfy a specific condition (based on class, id, attribute etc).
  • Know about the :not CSS pseudo-class.

The :not CSS pseudo-class can be used to select elements that do not contain a specific class, id, attribute etc.

Usually we need to select elements that satisfy a certain condition — they may have a certain class / attribute / id etc.

/* select all elements having class "menu-active" */
.menu-active {
	font-weight: 700;	
}

/* select all "p" elements */
p {
	line-height: 2;
}

/* select input elements having "text" type attribute */
input[type="text"] {
	display: block;
}

However many times we need just the opposite case — it may be required to select elements that are not having a specific class / attribute / id etc.

This can be achieved using the :not pseudo-class selector.

:not has a functional notation and takes a simple selector as its argument.

/* select all elements not having class "menu-active" */
:not(.menu-active) {
	font-weight: 300;
}

/* select "p" elements not having class "menu-active" */
p:not(.menu-active) {
	font-weight: 300;
}

/* select all elements except "p" */
:not(p) {
	line-height: normal;
}

/* select input elements not having "text" type attribute */
input:not([type="text"]) {
	display: inline-block;
}

Notes

Currently :not takes only a simple selector as its argument. No complex selectors are allowed.

Simple selectors can be :

  • Type selector

    p {
    	font-weight: 700;
    }
    
  • Universal selector

    * {
    	line-height: 1.5;
    }
    
  • Attribute selector

    input[type] {
    	font-size: 13px;
    }
    
    input[type="text"] {
    	font-size: 13px;
    }
    
  • Class selector

    .active {
    	background-color: blue;
    }
    
  • Id selector

    #sample {
    	border: 1px solid #cccccc;
    }
    
  • Pseudo class selector (however :not cannot be used as its own argument)

    a:focus {
    	text-decoration: underline;
    }
    
    p:first-child {
    	margin: 0;
    }
    

There are proposals to bring complex selectors as argument to :not. However most browsers have not implemented it yet.

Selecting Child Elements with CSS
Selecting Sibling Elements with CSS
Loading Comments