Bite 1: Your First CSS Selectors
Learn the basics of CSS selectors to target and style elements on a webpage.
What are CSS Selectors?
CSS selectors are used to “select” HTML elements that you want to style. Think of them as tools that help you point to parts of your webpage to apply visual changes.
In this lesson, we’ll learn three basic types of selectors:
- Tag Selector
- Class Selector
- ID Selector
Tag Selector
The tag selector targets all elements of a specific type. For example, if you want to change the color of all <p> tags, you use the tag selector.
Example:
p {
color: blue;
}
This code makes the text of all <p>
elements blue.
Class Selector
The class selector targets elements with a specific class attribute. Classes allow you to style multiple elements in the same way.
Syntax: Use a . before the class name.
Example:
.highlight {
background-color: yellow;
}
This code applies a yellow background to any element with the class highlight.
In your HTML:
<p class="highlight">This text has a yellow background.</p>
ID Selector
The ID selector targets a single, unique element with a specific ID attribute. IDs are meant to be unique within a page.
Syntax: Use a # before the ID name.
Example:
#important {
font-weight: bold;
}
This code makes the text bold for the element with the ID important.
In your HTML:
<p id="important">This text is bold because it is important!</p>
Putting It All Together
Here’s an example combining all three selectors:
Try It Yourself!
Summary
- Use tag selectors to style all elements of a specific type.
- Use class selectors (with .) to style multiple elements with the same class.
- Use ID selectors (with #) to style unique elements.
CSS selectors are the foundation of styling webpages. Practice using them, and you’ll be ready to create beautifully styled sites in no time!