CSS selectors define the elements to which a set of CSS rules apply.
The CSS universal selector (*
) matches elements of any type.
/* Selects all elements */
* {
color: green;
}
The CSS type selector matches elements by node name. In other words, it selects all elements of the given type within a document.
/* All <a> elements. */
a {
color: red;
}
The CSS class selector matches elements based on the contents of their class
attribute.
/* All elements with class="red" */
.red {
margin: 2em;
}
The CSS ID selector matches an element based on the value of the element’s id
attribute. In order for the element to be selected, its id
attribute must match exactly the value given in the selector.
/* The element with id="demo" */
#demo {
border: red 2px solid;
}
The CSS attribute selector matches elements based on the presence or value of a given attribute.
/* <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;
}
/* <a> elements whose class attribute contains the word "logo" */
a[class~="logo"] {
padding: 2px;
}
The descendant combinator — typically represented by a single space ( ``) character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor element matching the first selector.
/* List items that are descendants of the "my-things" list */
ul.my-things li {
margin: 2em;
}