Selectors

Introduction

CSS selectors identify specific HTML elements as targets for CSS styles. This topic covers how CSS selectors target HTML elements. Selectors use a wide range of over 50 selection methods offered by the CSS language, including elements, classes, IDs, pseudo-elements and pseudo-classes, and patterns.

Syntax

  • #id
  • .classname
  • :pseudo-classname
  • ::pseudo-elementname
  • [attr] /* has the attr attribute. */
  • [attr="value"] /* has the attr attribute, and its value is exactly "value". */
  • [attr~="value"] /* has the attr attribute, and its value, when split on whitespace, contains "value". */
  • [attr|="value"] /* has the attr attribute, and its value is exactly "value", or its value begins with "value-". */
  • [attr^="value"] /* has the attr attribute, and its value begins with "value". */
  • [attr$="value"] /* has the attr attribute, and its value ends with "value". */
  • [attr*="value"] /* has the attr attribute, and its value contains "value". */
  • element-name
  • *​

Remarks

  • Sometimes you will see double colons (::) instead of just one (:). This is a way to separate pseudo-classes from pseudo-elements.
  • Old browsers, like Internet Explorer 8, only support a single colon (:) for defining pseudo-elements.
  • Unlike pseudo-classes, only one pseudo-element may be used per selector, if present it must appear after the sequence of simple selectors that represents the subjects of the selector (a future version of the W3C specification may allow multiple pseudo-elements per selector).

Basic selectors

SelectorDescription
*Universal selector (all elements)
divTag selector (all <div> elements)
.blueClass selector (all elements with class blue)
.blue.redAll elements with class blue and red (a type of Compound selector)
#headlineID selector (the element with "id" attribute set to headline)
:pseudo-classAll elements with pseudo-class
::pseudo-elementElement that matches pseudo-element
:lang(en)Element that matches :lang declaration, for example <span lang="en">
div > pchild selector

Note: The value of an ID must be unique in a web page. It is a violation of the HTML standard to use the value of an ID more than once in the same document tree.

A complete list of selectors can be found in the CSS Selectors Level 3 specification.

A. The :not pseudo-class example & B. :focus-within CSS pseudo-class

A. The syntax is presented above.

The following selector matches all <input> elements in an HTML document that are not disabled and don't have the class .example:

HTML:

<form>
    Phone: <input type="tel" class="example">
    E-mail: <input type="email" disabled="disabled">
    Password: <input type="password">
</form>

CSS:

input:not([disabled]):not(.example){
   background-color: #ccc;
}

The :not() pseudo-class will also support comma-separated selectors in Selectors Level 4:

CSS:

input:not([disabled], .example){
   background-color: #ccc;
}

Live Demo on JSBin

See background syntax here.

B. The :focus-within CSS pseudo-class

HTML:

  <h3>Background is blue if the input is focused .</p>
  <div>
    <input type="text">
  </div>

CSS:

div {
  height: 80px;
}
input{
  margin:30px;
}
div:focus-within {
  background-color: #1565C0;
}

enter image description here enter image description here

Attribute Selectors

Overview

Attribute selectors can be used with various types of operators that change the selection criteria accordingly. They select an element using the presence of a given attribute or attribute value.

Selector(1)Matched elementSelects elements...CSS Version
[attr]<div attr>With attribute attr2
[attr='val']<div attr="val">Where attribute attr has value val2
[attr~='val']<div attr="val val2 val3">Where val appears in the
whitespace-separated list of attr
2
[attr^='val']<div attr="val1 val2">Where attr's value begins with val3
[attr$='val']<div attr="sth aval">Where the attr's value ends with val3
[attr*='val']<div attr="somevalhere">Where attr contains val anywhere3
[attr|='val']<div attr="val-sth etc">Where attr's value is exactly val,
or starts with val and immediately
followed by - (U+002D)
2
[attr='val' i]<div attr="val">Where attr has value val,
ignoring val's letter casing.
4(2)

Notes:

  1. The attribute value can be surrounded by either single-quotes or double-quotes. No quotes at all may also work, but it's not valid according to the CSS standard, and is discouraged.

  2. There is no single, integrated CSS4 specification, because it is split into separate modules. However, there are "level 4" modules. See browser support.

Details

[attribute]

Selects elements with the given attribute.

div[data-color] {
  color: red;
}
<div data-color="red">This will be red</div>
<div data-color="green">This will be red</div>
<div data-background="red">This will NOT be red</div>

Live Demo on JSBin

[attribute="value"]

Selects elements with the given attribute and value.

div[data-color="red"] {
  color: red;
}
<div data-color="red">This will be red</div>
<div data-color="green">This will NOT be red</div>
<div data-color="blue">This will NOT be red</div>

Live Demo on JSBin

[attribute*="value"]

Selects elements with the given attribute and value where the given attribute contains the given value anywhere (as a substring).

[class*="foo"] {
  color: red;
}
<div class="foo-123">This will be red</div>
<div class="foo123">This will be red</div>
<div class="bar123foo">This will be red</div>
<div class="barfooo123">This will be red</div>
<div class="barfo0">This will NOT be red</div>

Live Demo on JSBin

[attribute~="value"]

Selects elements with the given attribute and value where the given value appears in a whitespace-separated list.

[class~="color-red"] {
  color: red;
}
<div class="color-red foo-bar the-div">This will be red</div>
<div class="color-blue foo-bar the-div">This will NOT be red</div>

Live Demo on JSBin

[attribute^="value"]

Selects elements with the given attribute and value where the given attribute begins with the value.

[class^="foo-"] {
  color: red;
}
<div class="foo-123">This will be red</div>
<div class="foo-234">This will be red</div>
<div class="bar-123">This will NOT be red</div>

Live Demo on JSBin

[attribute$="value"]

Selects elements with the given attribute and value where the given attribute ends with the given value.

[class$="file"] {
  color: red;
}
<div class="foobar-file">This will be red</div>
<div class="foobar-file">This will be red</div>
<div class="foobar-input">This will NOT be red</div>

Live Demo on JSBin

[attribute|="value"]

Selects elements with a given attribute and value where the attribute's value is exactly the given value or is exactly the given value followed by - (U+002D)

[lang|="EN"] {
  color: red;
}
<div lang="EN-us">This will be red</div>
<div lang="EN-gb">This will be red</div>
<div lang="PT-pt">This will NOT be red</div>

Live Demo on JSBin

[attribute="value" i]

Selects elements with a given attribute and value where the attribute's value can be represented as Value, VALUE, vAlUe or any other case-insensitive possibility.

[lang="EN" i] {
  color: red;
}
<div lang="EN">This will be red</div>
<div lang="en">This will be red</div>
<div lang="PT">This will NOT be red</div>

Live Demo on JSBin

Specificity of attribute selectors

0-1-0

Same as class selector and pseudoclass.

*[type=checkbox] // 0-1-0

Note that this means an attribute selector can be used to select an element by its ID at a lower level of specificity than if it was selected with an ID selector: [id="my-ID"] targets the same element as #my-ID but with lower specificity.

See the Syntax Section for more details.

Child Pseudo Class

"The :nth-child(an+b) CSS pseudo-class matches an element that has an+b-1 siblings before it in the document tree, for a given positive or zero value for n" - MDN :nth-child

pseudo-selector12345678910
:first-child
:nth-child(3)
:nth-child(n+3)
:nth-child(3n)
:nth-child(3n+1)
:nth-child(-n+3)
:nth-child(odd)
:nth-child(even)
:last-child
:nth-last-child(3)

Class Name Selectors

The class name selector select all elements with the targeted class name. For example, the class name .warning would select the following <div> element:

<div class="warning">
    <p>This would be some warning copy.</p>
</div>

You can also combine class names to target elements more specifically. Let's build on the example above to showcase a more complicated class selection.

CSS

.important {
    color: orange;
}
.warning {
    color: blue;
}
.warning.important {
    color: red;
}

HTML

<div class="warning">
    <p>This would be some warning copy.</p>
</div>

<div class="important warning">
    <p class="important">This is some really important warning copy.</p>
</div>

In this example, all elements with the .warning class will have a blue text color, elements with the .important class with have an orange text color, and all elements that have both the .important and .warning class name will have a red text color.

Notice that within the CSS, the .warning.important declaration did not have any spaces between the two class names. This means it will only find elements which contain both class names warning and important in their class attribute. Those class names could be in any order on the element.

If a space was included between the two classes in the CSS declaration, it would only select elements that have parent elements with a .warning class names and child elements with .important class names.

Combinators

Overview

SelectorDescription
div spanDescendant selector (all <span>s that are descendants of a <div>)
div > spanChild selector (all <span>s that are a direct child of a <div>)
a ~ spanGeneral Sibling selector (all <span>s that are siblings after an <a>)
a + spanAdjacent Sibling selector (all <span>s that are immediately after an <a>)

Note: Sibling selectors target elements that come after them in the source document. CSS, by its nature (it cascades), cannot target previous or parent elements. However, using the flex order property, a previous sibling selector can be simulated on visual media.

Descendant Combinator: selector selector

A descendant combinator, represented by at least one space character (), selects elements that are a descendant of the defined element. This combinator selects all descendants of the element (from child elements on down).

div p {
  color:red;
}
<div>
  <p>My text is red</p>
  <section>
    <p>My text is red</p>
  </section>
</div>

<p>My text is not red</p>

Live Demo on JSBin

In the above example, the first two <p> elements are selected since they are both descendants of the <div>.


Child Combinator: selector > selector

The child (>) combinator is used to select elements that are children, or direct descendants, of the specified element.

div > p {
  color:red;
}
<div>
  <p>My text is red</p>
  <section>
    <p>My text is not red</p>
  </section>
</div>

Live Demo on JSBin

The above CSS selects only the first <p> element, as it is the only paragraph directly descended from a <div>.

The second <p> element is not selected because it is not a direct child of the <div>.


Adjacent Sibling Combinator: selector + selector

The adjacent sibling (+) combinator selects a sibling element that immediate follows a specified element.

p + p {
  color:red;
}
<p>My text is not red</p>
<p>My text is red</p>
<p>My text is red</p>
<hr>
<p>My text is not red</p>

Live Demo on JSBin

The above example selects only those <p> elements which are directly preceded by another <p> element.


General Sibling Combinator: selector ~ selector

The general sibling (~) combinator selects all siblings that follow the specified element.

p ~ p {
  color:red;
}
<p>My text is not red</p>
<p>My text is red</p>
<hr>
<h1>And now a title</h1>
<p>My text is red</p>

Live Demo on JSBin

The above example selects all <p> elements that are preceded by another <p> element, whether or not they are immediately adjacent.

CSS3 :in-range selector example

<style>
input:in-range {
    border: 1px solid blue;
}
</style>



<input type="number" min="10" max="20" value="15">
<p>The border for this value will be blue</p>

The :in-range CSS pseudo-class matches when an element has its value attribute inside the specified range limitations for this element. It allows the page to give a feedback that the value currently defined using the element is inside the range limits.[1]

Global boolean with checkbox:checked and ~ (general sibling combinator)

With the ~ selector, you can easily implement a global accessible boolean without using JavaScript.

Add boolean as a checkbox

To the very beginning of your document, add as much booleans as you want with a unique id and the hidden attribute set:

<input type="checkbox" id="sidebarShown" hidden />
<input type="checkbox" id="darkThemeUsed" hidden />

<!-- here begins actual content, for example: -->
<div id="container">
    <div id="sidebar">
        <!-- Menu, Search, ... -->
    </div>

    <!-- Some more content ... -->
</div>

<div id="footer">
    <!-- ... -->
</div>

Change the boolean's value

You can toggle the boolean by adding a label with the for attribute set:

<label for="sidebarShown">Show/Hide the sidebar!</label>

Accessing boolean value with CSS

The normal selector (like .color-red) specifies the default properties. They can be overridden by following true / false selectors:

/* true: */
<checkbox>:checked ~ [sibling of checkbox & parent of target] <target>

/* false: */
<checkbox>:not(:checked) ~ [sibling of checkbox & parent of target] <target>

Note that <checkbox>, [sibling ...] and <target> should be replaced by the proper selectors. [sibling ...] can be a specific selector, (often if you're lazy) simply * or nothing if the target is already a sibling of the checkbox.

Examples for the above HTML structure would be:

#sidebarShown:checked ~ #container #sidebar {
    margin-left: 300px;
}

#darkThemeUsed:checked ~ #container,
#darkThemeUsed:checked ~ #footer {
    background: #333;
}

In action

See this fiddle for a implementation of these global booleans.

How to style a Range input

HTML

<input type="range"></input>

CSS

EffectPseudo Selector
Thumbinput[type=range]::-webkit-slider-thumb, input[type=range]::-moz-range-thumb, input[type=range]::-ms-thumb
Trackinput[type=range]::-webkit-slider-runnable-track, input[type=range]::-moz-range-track, input[type=range]::-ms-track
OnFocusinput[type=range]:focus
Lower part of the trackinput[type=range]::-moz-range-progress, input[type=range]::-ms-fill-lower (not possible in WebKit browsers currently - JS needed)

ID selectors

ID selectors select DOM elements with the targeted ID. To select an element by a specific ID in CSS, the # prefix is used.

For example, the following HTML div element…

<div id="exampleID">
    <p>Example</p>
</div>

…can be selected by #exampleID in CSS as shown below:

#exampleID {
    width: 20px;
}

Note: The HTML specs do not allow multiple elements with the same ID

Pseudo-classes

Pseudo-classes are keywords which allow selection based on information that lies outside of the document tree or that cannot be expressed by other selectors or combinators. This information can be associated to a certain state (state and dynamic pseudo-classes), to locations (structural and target pseudo-classes), to negations of the former (negation pseudo-class) or to languages (lang pseudo-class). Examples include whether or not a link has been followed (:visited), the mouse is over an element (:hover), a checkbox is checked (:checked), etc.

Syntax

selector:pseudo-class { 
    property: value;
}

List of pseudo-classes:

NameDescription
:activeApplies to any element being activated (i.e. clicked) by the user.
:anyAllows you to build sets of related selectors by creating groups that the
included items will match. This is an alternative to repeating an entire selector.
:targetSelects the current active #news element (clicked on a URL
containing that anchor name)
:checkedApplies to radio, checkbox, or option elements that are checked
or toggled into an "on" state.
:defaultRepresents any user interface element that is the default among a group of
similar elements.
:disabledApplies to any UI element which is in a disabled state.
:emptyApplies to any element which has no children.
:enabledApplies to any UI element which is in an enabled state.
:firstUsed in conjunction with the @page rule, this selects the first page in a
printed document.
:first-childRepresents any element that is the first child element of its parent.
:first-of-typeApplies when an element is the first of the selected element type
inside its parent. This may or may not be the first-child.
:focusApplies to any element which has the user's focus. This can be given by the
user's keyboard, mouse events, or other forms of input.
:focus-withinCan be used to highlight a whole section when one element inside it is focused. It matches any element that the :focus pseudo-class matches or that has a descendant focused.
:full-screenApplies to any element displayed in full-screen mode. It selects the whole stack
of elements and not just the top level element.
:hoverApplies to any element being hovered by the user's pointing device, but
not activated.
:indeterminateApplies radio or checkbox UI elements which are neither checked nor
unchecked, but are in an indeterminate state. This can be due to an
element's attribute or DOM manipulation.
:in-rangeThe :in-range CSS pseudo-class matches when an element has
its value attribute inside the specified range limitations for this element.
It allows the page to give a feedback that the value currently defined
using the element is inside the range limits.
:invalidApplies to <input> elements whose values are invalid according to
the type specified in the type= attribute.
:langApplies to any element who's wrapping <body> element has a properly
designated lang= attribute. For the pseudo-class to be valid, it must
contain a valid two or three letter language code.
:last-childRepresents any element that is the last child element of its parent.
:last-of-typeApplies when an element is the last of the selected element type inside
its parent. This may or may not be the last-child.
:leftUsed in conjunction with the @page rule, this selects all the left
pages in a printed document.
:linkApplies to any links which haven't been visited by the user.
:not()Applies to all elements which do not match the value passed to
(:not(p) or :not(.class-name) for example. It must have a value to be
valid and it can only contain one selector. However, you can chain multiple :not selectors together.
:nth-childApplies when an element is the n-th element of its parent, where n
can be an integer, a mathematical expression (e.g n+3) or the keywords
odd or even.
:nth-of-typeApplies when an element is the n-th element of its parent of the
same element type, where n can be an integer, a mathematical
expression (e.g n+3) or the keywords odd or even.
:only-childThe :only-child CSS pseudo-class represents any element
which is the only child of its parent. This is the same as
:first-child:last-child or :nth-child(1):nth-last-child(1),
but with a lower specificity.
:optionalThe :optional CSS pseudo-class represents any element
that does not have the required attribute set on it. This allows
forms to easily indicate optional fields and to style them accordingly.
:out-of-rangeThe :out-of-range CSS pseudo-class matches when an element has its
value attribute outside the specified range limitations for this element.
It allows the page to give a feedback that the value currently defined using the
element is outside the range limits. A value can be outside of a range if it is
either smaller or larger than maximum and minimum set values.
:placeholder-shownExperimental. Applies to any form element currently displaying placeholder text.
:read-onlyApplies to any element which is not editable by the user.
:read-writeApplies to any element that is editable by a user, such as <input> elements.
:rightUsed in conjunction with the @page rule, this selects all the right pages in a
printed document.
:rootmatches the root element of a tree representing the document.
:scopeCSS pseudo-class matches the elements that are a reference
point for selectors to match against.
:targetSelects the current active #news element (clicked on a URL
containing that anchor name)
:visitedApplies to any links which have has been visited by the user.

The :visited pseudoclass can't be used for most styling in a lot of modern browsers anymore because it's a security hole. See this link for reference.

Select element using its ID without the high specificity of the ID selector

This trick helps you select an element using the ID as a value for an attribute selector to avoid the high specificity of the ID selector.

HTML:

<div id="element">...</div>  

CSS

#element { ... } /* High specificity will override many selectors */

[id="element"] { ... } /* Low specificity, can be overridden easily */

The :last-of-type selector

The :last-of-type selects the element that is the last child, of a particular type, of its parent. In the example below, the css selects the last paragraph and the last heading h1.

p:last-of-type { 
  background: #C5CAE9; 
}
h1:last-of-type { 
  background: #CDDC39; 
}
<div class="container">
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <p>Last paragraph</p>
    <h1>Heading 1</h1>
    <h2>First heading 2</h2>
    <h2>Last heading 2</h2>
</div>

enter image description here

jsFiddle

The :only-child pseudo-class selector example

The :only-child CSS pseudo-class represents any element which is the only child of its parent.

HTML:

<div>
  <p>This paragraph is the only child of the div, it will have the color blue</p>
</div>

<div>
  <p>This paragraph is one of the two children of the div</p>
  <p>This paragraph is one of the two children of its parent</p>
</div>

CSS:

p:only-child {
  color: blue;
}

The above example selects the <p> element that is the unique child from its parent, in this case a <div>.

Live Demo on JSBin