Selector - 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 Selector
A grouping selector combines multiple selectors to create more complex selectors.
- Comma (,): Combines two or more selectors. For example,
p, h1
selects allp
elements and allh1
elements.
/* Applies the same style to p and h1 elements using the grouping selector */
p,
h1 {
color: blue; /* Sets the text color to blue */
}
Combinators
Combinators combine selectors to create more complex selectors.
-
Adjacent Sibling Combinator (+): Selects the next sibling of the selector. For example,
p + h1
selects anyh1
element that is immediately preceded by ap
element. -
General Sibling Combinator (~): Selects any sibling that follows the selector. For example,
p ~ h1
selects anyh1
elements that follow ap
element.
/* Applies style to the h1 element immediately following the p element using the adjacent sibling combinator */
p + h1 {
color: red; /* Sets the text color to red */
}
/* Applies style to all h1 elements following the p element using the general sibling combinator */
p ~ h1 {
border-bottom: 2px solid black; /* Adds a black border at the bottom with a thickness of 2px */
}
Pseudo-Selectors
Pseudo-selectors select elements that match specific conditions.
-
Structural Pseudo-Selectors: Specify the format of elements. For example,
:empty
selects empty elements. -
State Pseudo-Selectors: Specify the state of elements. For example,
:hover
is applied when the mouse is over the element. -
Relational Pseudo-Selectors: Specify the relationship of elements. For example,
:nth-child()
specifies the order of elements.
/* Applies style to empty elements using the structural pseudo-selector */
:empty {
background-color: lightgray; /* Sets the background color to light gray */
}
/* Applies style when the mouse is over the element using the state pseudo-selector */
a:hover {
text-decoration: underline; /* Adds an underline */
color: orange; /* Sets the text color to orange */
}
/* Applies style to the third child element of a ul using the relational pseudo-selector */
ul:nth-child(3) {
font-weight: bold; /* Sets the font weight to bold */
}
Follow the parts emphasized with asterisks in the code.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.