CSS selectors are used to "select" the HTML elements you want to style. They are one of the core features of CSS, allowing you to apply styles to elements based on various attributes.
Basic selectors are used to select elements based on their name, class, or ID:
/* Element Selector */
p {
color: blue;
}
/* Class Selector */
.special {
color: green;
}
/* ID Selector */
#unique {
color: red;
}
This is a paragraph styled with the element selector.
This paragraph is styled with the class selector.
This paragraph is styled with the ID selector.
You can group multiple selectors to apply the same styles to multiple elements:
h1, h2, p {
color: purple;
}
This paragraph is also styled with the same grouped selector.
Combinator selectors are used to select elements based on a relationship between them:
/* Descendant Selector */
div p {
color: blue;
}
/* Child Selector */
div > p {
color: green;
}
/* Adjacent Sibling Selector */
h1 + p {
color: red;
}
/* General Sibling Selector */
h1 ~ p {
color: purple;
}
This paragraph is selected by the descendant selector.
This paragraph is selected by the child selector.
This paragraph is selected by the adjacent sibling selector.
This paragraph is selected by the general sibling selector.
Attribute selectors allow you to select elements based on the presence or value of an attribute:
/* Attribute Selector */
a[target] {
color: orange;
}
/* Attribute Value Selector */
a[target="_blank"] {
color: purple;
}
Pseudo-classes are used to define a special state of an element. Pseudo-elements are used to style specified parts of an element:
/* Pseudo-class Selector */
a:hover {
color: red;
}
/* Pseudo-element Selector */
p::first-line {
font-weight: bold;
}