Back to Blog

CSS Selectors and Specificity

Selectors

CSS uses the chaining of selectors to target elements in the HTML and style them. Choosing the right CSS selectors can prevent unwanted style changes and unnecessary lines of code. The table below shows the basic selectors used in CSS.

SelectorSyntaxDescription
Universal*All elements.
Class.class-nameElements that share the class name.
ID#idElement matching the ID.
TypetypeElements of the given type.
Attribute[attribute=value]Elements with selected attribute.
Pseudo-classelement:pseudo-classElements in different states, such as hover or focus.
Pseudo-elementelement::pseudo-elementParts of an element not specified in the HTML.

Selectors can be chained together using combinators. Combinators are inserted between basic selectors and allow the targeting of very specific elements for styling.

There are four CSS combinators:

  • 'space' : Descendant
  • (>) : Child
  • (+) : Adjacent Sibling
  • (~) : General Sibling

Below are a few examples of interesting ways selectors can be used to style a page.

Alternating Elements

The :nth-of-type() psuedo-class targets elements based on their order in the DOM. It can be passed a numerical argument, or can be passed odd or even to select alternating elements. The following code demonstrates how to make even-numbered paragraphs red.

p:nth-of-type(even) {
  color: red;
}

List Markers

The ::marker pseudo-element is used to style the markers on unordered lists. This allows color changes, size changes, and animations.

Code:

ul li::marker {
  color: orange;
  font-size: 24px;
}

Result:

  • Item 1
  • Item 2

Spans

The following code will only style a span that is within a paragraph with the class of 'text'.

p.text > span {
  color: red;
}

Specificity

It is common to have multiple CSS rules targeting an individual element. Because these rules can be conflicting, the browser needs to calculate which rule to follow. This is done by determining the specificity of the selectors used to target the element.

Each selector applied in a CSS rule has a specificity value that contributes to the overall specificity of the rule. The rules with the most specificity are the ones applied when rendering the page.

This table shows the weight values of selectors:

SelectorWeight
ID1 0 0
Class0 1 0
Type0 0 1

Rules with an ID selector have more specificity than those with a class selector. The specificity of chained selectors can be determined by adding together their values according to the weight chart above. The only two cases in which ID-selected styles will be overwritten are by using inline styles or the !important flag.

Inline Styles

Inline styles, styles written in the HTML or JSX directly, are given a higher specificity than ID selectors.

!important

The !important flag can be added to a CSS rule to override other CSS rules. Rules marked with this flag will override inline styles.