본문으로 건너뛰기

Selectors - Advanced

Selectors - Advanced

The selectors introduced earlier are the most basic selectors for applying CSS.

This time, let's combine selectors to create more complex selectors.


Grouping Selectors

Grouping selectors allow you to combine multiple selectors to create a more complex selector.

  • Comma (,): Combines two or more selectors. For example, p, h1 selects all p elements and all h1 elements.
CSS
/* Using grouping selectors to apply the same style to p and h1 elements */
p,
h1 {
color: blue; /* Sets the text color to blue */
}

Combinators

Combinators allow you to combine selectors to create a more complex selector.

  • Adjacent Sibling Combinator (+): Selects the immediate next sibling of the selector. For example, p + h1 selects all h1 elements that are the immediate next siblings of all p elements.

  • General Sibling Combinator (~): Selects one of the siblings of the selector. For example, p ~ h1 selects all h1 elements that are siblings of any p elements.

CSS
/* Using the adjacent sibling combinator to style the h1 element that directly follows p element */
p + h1 {
color: red; /* Sets the text color to red */
}

/* Using the general sibling combinator to style all h1 elements that follow p elements */
p ~ h1 {
border-bottom: 2px solid black; /* Adds a 2px thick black border to the bottom */
}

Pseudo-Selectors

Pseudo-selectors select elements that meet certain conditions.

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

  • State pseudo-selectors: Specify the state of elements. For example, :hover selects elements when the mouse is over them.

  • Relationship pseudo-selectors: Specify the relationship of elements. For example, :nth-child() specifies the order of elements.

CSS
/* Using structural pseudo-selectors to style empty elements */
:empty {
background-color: lightgray; /* Sets the background color to light gray */
}

/* Using state pseudo-selectors to style elements when the mouse is over them */
a:hover {
text-decoration: underline; /* Adds underline */
color: orange; /* Sets the text color to orange */
}

/* Using relationship pseudo-selectors to style the third child of ul */
ul:nth-child(3) {
font-weight: bold; /* Sets the font weight to bold */
}

Follow along with the parts of the code emphasized with asterisks.