Chapter 3. Selectors

Selectors

Universal Selector

Pattern:

*

Description:

This selector matches any element name in the document’s language. If a rule does not have an explicit selector, the universal selector is inferred.

Examples:
* {color: red;}
div * p {color: blue;}

Type Selector

Pattern:

element1

Description:

This selector matches the name of an element in the document’s language. Every instance of the element name is matched. (CSS1 referred to these as “element selectors.”)

Examples:
body {background: #FFF;}
p {font-size: 1em;}

Descendant Selector

Pattern:

element1 element2

Description:

This allows the author to select an element based on its status as a descendant of another element. The matched element can be a child, grandchild, great-grandchild, etc., of the ancestor element. (CSS1 referred to these as “contextual selectors.”)

Examples:
body h1 {font-size: 200%;}
table tr td div ul li {color: purple;}

Child Selector

Pattern:

element1 > element2

Description:

This type of selector is used to match an element based on its status as a child of another element. It is more restrictive than a descendant selector, as only a child will be matched.

Examples:
div > p {color: cyan;}
ul > li {font-weight: bold;}

Adjacent Sibling Selector

Pattern:

element1 + element2

Description:

This allows the author to select an element that is the following adjacent sibling of another element. (Sibling elements, as the name implies, share the same parent element.) Any text between the two elements is ignored; only elements ...

Get CSS Pocket Reference, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.