Basic Selectors: Type, Class, and ID
You'll learn the three foundational ways to target HTML elements with CSS so you can apply styles precisely where you want them.
What Are Selectors?
CSS selectors are patterns that tell the browser which HTML elements to style. Think of them like addressing a letter—you need to specify exactly who should receive it. The three basic selectors give you different levels of targeting precision.
Type Selector (Element Selector)
The type selector targets all elements of a specific HTML type. Use the element name directly:
p {
color: blue;
}
This styles every <p> element on the page. It's broad and affects many elements at once—great for setting baseline styles.
Class Selector
The class selector targets elements with a specific class attribute. Use a dot (.) followed by the class name:
.highlight {
background-color: yellow;
}
<p class="highlight">This paragraph is highlighted.</p>
<p>This one is not.</p>
Classes are reusable—you can apply the same class to multiple elements of any type. This is your workhorse selector for styling groups of elements.
ID Selector
The ID selector targets one unique element with a specific id attribute. Use a hash (#) followed by the ID name:
#site-header {
font-size: 24px;
}
<header id="site-header">Welcome</header>
IDs must be unique on a page—use them sparingly for one-off, specific elements.
When to Use Each
- Type selectors: Default styles for all elements of that type
- Class selectors: Reusable styles for groups of elements (most common)
- ID selectors: Unique, one-time targeting (use rarely in CSS)
Key Takeaway: Type selectors target all elements of a kind, class selectors (.classname) target reusable groups, and ID selectors (#idname) target single unique elements—together they form the foundation of all CSS targeting.