CSS selectors are used to select and style specific HTML elements. There are several types of selectors in CSS:
- Tag selectors: Select elements based on their tag name. For example, the following CSS code selects all
<p>
elements and sets their color to blue:
p {
color: blue;
}
2. Class selectors: Select elements based on their class attribute. For example, the following CSS code selects all elements with the class “my-class” and sets their color to red:
.my-class {
color: red;
}
In HTML, the class attribute is used to assign one or more classes to an element, like this: <div class="my-class">...</div>
.
- ID selectors: Select elements based on their ID attribute. For example, the following CSS code selects the element with the ID “my-id” and sets its background color to yellow:
#my-id {
background-color: yellow;
}
In HTML, the ID attribute is used to give a unique ID to an element, like this: <div id="my-id">...</div>
.
- Attribute selectors: Select elements based on their attributes. For example, the following CSS code selects all
<a>
elements with the “href” attribute containing the word “example” and sets their color to green:
a[href*="example"] {
color: green;
}
This is called a substring matching attribute selector. There are also other types of attribute selectors, such as exact matching, prefix matching, and suffix matching.
- Pseudo-classes: Select elements based on their state or position. For example, the following CSS code selects all
<a>
elements when the mouse hovers over them and sets their color to red:
a:hover {
color: red;
}
Other common pseudo-classes include :active
(when the element is being clicked), :visited
(when the link has been visited), and :first-child
(when the element is the first child of its parent).
- Pseudo-elements: Select and style parts of an element. For example, the following CSS code adds a double border to the first letter of all
<p>
elements:
p::first-letter {
border: 2px double black;
}
This is called a pseudo-element. Other common pseudo-elements include ::before
and ::after
.
These are some of the most common CSS selectors, but there are many others that allow you to target elements based on their relationships with other elements, their position in the document, and more.