CSS selectors are used to select HTML elements on the page that you want to style. There are different types of selectors, including:
These target HTML tags directly. For example, p
targets all paragraph elements.
p { color: red; }
These target elements with a specific class attribute. Class selectors are prefixed with a .
.
.example { color: blue; }
These target elements with a specific ID attribute. ID selectors are prefixed with a #
.
#unique { color: green; }
The universal selector targets all elements on the page. It is represented by *
.
* { margin: 0; padding: 0; }
These target elements based on their attributes. For example, to target links with the href
attribute:
a[href] { color: orange; }
These select elements based on their state or position. For example, :hover
targets an element when the user hovers over it.
a:hover { color: purple; }
These allow you to style part of an element. For example, ::before
adds content before an element.
p::before { content: "Prefix: "; }
Specificity is how the browser decides which styles to apply when multiple CSS rules match the same element. The more specific a selector, the higher its priority.
The color of the text below will depend on which CSS rule has higher specificity.
/* Style 1: Element selector */
div {
color: yellow;
}
/* Style 2: ID selector */
#test {
color: red;
}
/* Style 3: Class selector */
.selector-box {
color: blue;
}
The final color of the text in the box will be red because the ID selector has higher specificity than the class and element selectors.
1. Which CSS selector targets an element with a specific class?
2. Which selector has the highest specificity?
3. What happens when two CSS rules with the same specificity conflict?