CSS selectors are used to target HTML elements for styling. This page covers different types of CSS selectors and how to use them.
CSS selectors are categorized based on how they target elements. Here are some commonly used selectors:
Targets elements by their tag name.
/* Element Selector */
p {
color: blue;
}
Styles all <p>
elements with color: blue;
.
Targets elements with a specific class name.
/* Class Selector */
.button {
background-color: green;
color: white;
}
Styles all elements with the class button
.
Targets a unique element with a specific ID.
/* ID Selector */
#header {
font-size: 24px;
font-weight: bold;
}
Styles the element with the ID header
.
Targets elements based on their attributes and values.
/* Attribute Selector */
input[type="text"] {
border: 1px solid gray;
}
Styles <input>
elements with type="text"
.
Applies the same style to multiple elements.
/* Group Selector */
h1, h2, h3 {
color: darkblue;
}
Styles <h1>
, <h2>
, and <h3>
elements with color: darkblue;
.
Targets elements nested within other elements.
/* Descendant Selector */
div p {
color: red;
}
Styles <p>
elements inside a <div>
with color: red;
.
Targets elements based on their state or position.
/* Pseudo-class Selector */
a:hover {
color: orange;
}
Styles <a>
elements when hovered over with color: orange;
.
Targets specific parts of an element.
/* Pseudo-element Selector */
p::first-line {
font-weight: bold;
}
Styles the first line of all <p>
elements with font-weight: bold;
.