Lecture

Advanced Selectors

Previously, we introduced the most basic selectors for applying CSS.

Now, let's combine selectors to create more complex selectors.


Grouping Selectors

Grouping selectors allow you to combine multiple selectors to create more complex ones.

Use a comma (,) to group two or more selectors.

For example, p, h1 selects all p elements and all h1 elements.

CSS
/* Apply the same style to p and h1 elements using grouping selectors */ p, h1 { color: blue; /* Set the text color to blue */ }

Combinators

Combinators combine selectors to create more complex selectors.


Adjacent Sibling Combinator (+)

Selects the next sibling of a selector.

For example, p + h1 selects every h1 element that immediately follows a p element.


General Sibling Combinator (~)

Selects any sibling of a selector.

For example, p ~ h1 selects every h1 element that is a sibling of a p element.

CSS
/* Apply styles to an h1 element immediately following a p element using the adjacent sibling combinator */ p + h1 { color: red; /* Set the text color to red */ } /* Apply styles to all h1 elements following a p element using the general sibling combinator */ p ~ h1 { border-bottom: 2px solid black; /* Add a 2px solid black border at the bottom */ }

Pseudo-Selectors

Pseudo-selectors select elements that meet specific conditions.

  • Structural pseudo-selectors: Specify the structure of an element. For example, :empty selects elements that are empty.

  • State pseudo-selectors: Specify the state of an element. For example, :hover styles an element when the mouse is over it.

  • Relational pseudo-selectors: Specify the relationship of elements. For example, :nth-child() specifies which child element to select.

CSS
/* Apply styles to empty elements using a structural pseudo-selector */ :empty { background-color: lightgray; /* Set the background color to light gray */ } /* Apply styles when the mouse is over an element using a state pseudo-selector */ a:hover { text-decoration: underline; /* Add an underline */ color: orange; /* Set the text color to orange */ } /* Apply styles to the third child of ul using a relational pseudo-selector */ ul:nth-child(3) { font-weight: bold; /* Set the font weight to bold */ }

Follow the highlighted sections in the code to input them.

Mission
0 / 1

A grouping selector can combine multiple selectors to apply the same style.

True
False

Lecture

AI Tutor

Design

Upload

Notes

Favorites

Help

HTML
CSS
Loading...