CSS Selectors

CSS Selectors

In CSS, selectors are patterns used to select the elements that you want to apply the style to.

Class

Usage: .classname will select any element that has class=”classname”


ID

Usage: #myId will select any element that has id=”myId”. There should always only be one element in a document with a given ID.


Attribute

Selects elements based on the value of the given attribute
Usage: [attr] [attr=value]
More Examples:

/* <a> elements with a title attribute */
a[title] {
  color: purple;
}

/* <a> elements with an href matching "https://example.org" */
a[href="https://example.org"] {
  color: green;
}

/* <a> elements with an href containing "example" */
a[href*="example"] {
  font-size: 2em;
}

/* <a> elements with an href ending ".org" */
a[href$=".org"] {
  font-style: italic;
}

[attr]
Represents an element with an attribute name of attr.

[attr=value]
Represents an element with an attribute name of attr whose value is exactly value.

[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.

[attr|=value]
Represents an element with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, – (U+002D). It is often used for language subcode matches.

[attr^=value]
Represents an element with an attribute name of attr whose value is prefixed by value.

[attr$=value]
Represents an element with an attribute name of attr whose value is suffixed by value.

[attr*=value]
Represents an element with an attribute name of attr whose value contains at least one occurrence of value within the string.

[attr operator value i]
Adding an i (or I) before the closing bracket causes the value to be compared case-insensitively


Pseudo-classes

Allows the selection of elements based on state information that is not contained in the document tree.

Examples: :active :disabled :focus :visited


Sibling

Adjacent sibling: The + combinator selects adjacent siblings. This means that the second element directly follows the first, and both share the same parent.
Example: h2 + p will match all <p> elements that directly follow an <h2>.

General siblings: The ~ combinator selects siblings. This means that the second element follows the first (though not necessarily immediately), and both share the same parent.
Example: p ~ span will match all <span> elements that follow a <p>.

Child combinator: The > combinator selects nodes that are direct children of the first element.
Example: ul > li will match all <li> elements that are nested directly inside a <ul> element.

Descendant combinator: The     (space) combinator selects nodes that are descendants of the first element.
Example: div span will match all <span> elements that are inside a <div> element.