tree_title | description | last_modified |
---|---|---|
Selectors |
An overview of CSS selectors and how to combine them |
2020-05-30 15:54:15 +0200 |
Selects based on HTML element type
h1 {
color: red;
}
Selects all elements
* {
color: red;
}
Selects elements based on class
.error-text {
color: red;
}
Selects elements based on ID
#main-text {
color: black;
}
Select elements based on attributes
[disabled] {
color: red;
}
Selects elements that are in a specific state
Typically combined with other selectors (see also below)
a:hover {
color: red;
}
Special case: the negation pseudo-class
/* matches any element that is not a paragraph */
:not(p) {
color: blue;
}
Selects specific part of an element
Typically combined with other selectors
p::first-line {
text-transform: uppercase;
}
No effect other than reducing code duplication
Example: before
h1 {
color: blue;
}
.special {
color: blue;
}
Example: after
h1, .special {
color: blue;
}
Combine multiple selectors that all need to apply to the same element
Example: select all hyperlinks with class test
that the user hovers over
a.test:hover {
color: red;
}
Typically represented by a single space (
) character
Elements matched by the second selector are selected if they have an ancestor matching the first selector
Example: select all spans that are directly or indirectly inside a div with class test
div.test span {
color: red;
}
Represented by the >
sign
Same as descendant combinator, but only considers the direct parent of an element
Example: select all spans that are a direct child of a div with class test
div.test > span {
color: red;
}
Represented by the +
sign
Matches an element matching the second selector if that element immediately follows an element matching the first selector and they both have the same parent
Example: select all paragraphs that immediately follow an image
img + p {
color: red;
}
Represented by the ~
sign
Matches an element matching the second selector if that element follows an element matching the first selector (but not necessarily immediately) and they both have the same parent
Example: select paragraphs that come after any image with the same parent
img ~ p {
color: red;
}