CSS Selectors

CSS selectors select which HTML element(s) is affected by a group of CSS rules.

Basic Selectors

You can combine more than one of these selectors to make an "and" clause. E.g.,

  • p.foo.bar will select all <p> elements with classes foo and bar
  • p.foo#bar will select all <p> elements with class foo and ID bar
SyntaxDescription
Basic selectors
*Universal selector — selects all elements
fooType selector — selects all <foo> elements
.classnameClass selector — selects all elements whose class="..." value includes classname
#idnameID selector — selects all elements whose id="..." value is idname
Attribute selectors
[attr]Selects all elements that specifies an attr attribute (set to whatever value)
[attr="value"]"Exact match" — selects all elements whose attr="..." value is exactly value
[attr~="value"]"Word match" — selects all elements whose attr="..." value is a whitespace-separated list of words, one of which is exactly value
[attr|="value"]"Prefix-hyphen match" — selects all elements whose attr="..." value is value or begins with value- (usually used for language subcode matches)
[attr^="value"]"Prefix match" — selects all elements whose attr="..." value begins with value
[attr$="value"]"Suffix match" — selects all elements whose attr="..." value ends with value
[attr*="value"]"Substring match" — selects all elements whose attr="..." value has the substring value
Attribute selectors — case match
[... i]E.g. [attr="value" i] — make matching value case insensitive
[... s]E.g. [attr="value" s] — make matching value case sensitive

Basic selector with namespace

We omit discussion about basic selectors with a namespace, e.g. ns|* or ns|div, where ns is the name of the namespace defined with the @namespace syntax.

This usually only makes sense when we're dealing with other XML-like formats (like SVG or MathML). You can read more about this here.

Grouping Selectors

Using , allows you to make an "or" clause. E.g.,

  • div, span will select all <div> and <span> elements.

Combinators

Combinators allow you to select elements based on their relative positions to other elements.

SyntaxDescription
div spanDescendant combinator — selects all <span> that are descendants of <div>
div > spanDescendant combinator — selects all <span> that are immediate child of <div>
h1 ~ pGeneral sibling combinator — selects all <p> that follows <h1>
h1 + pImmediate sibling combinator — selects all <p> that immediately follows <h1>
col || tdColumn combinator — selects all <td> that belongs to the span/scope of <col>

Pseudo

Pseudo selectors select something that is not actually there in the document tree.

SyntaxDescription
a:hoverPseudo class (:pseudoclass) — selects element based on its state information
a::beforePseudo element (::pseudoelement) — represents entitity not included in HTML

References