main-nav {
CSS selectors are one of the most fundamental and powerful aspects of CSS. As a web developer, understanding the different types of selectors and how to leverage them effectively is crucial for styling web pages with precision and flexibility.
In this comprehensive guide, we‘ll dive deep into the world of CSS selectors. You‘ll learn what they are, how they work, and some best practices and advanced techniques for using them in your projects. Whether you‘re new to CSS or an experienced pro, by the end you‘ll have expert-level knowledge of selectors to take your stylesheets to the next level.
What are CSS Selectors?
At its core, a CSS selector is a pattern used to select and style specific HTML elements in a web page. Selectors are what allow you to target only the elements you want without changing the styles of everything else.
For example, if you want all the
headings on your site to be navy blue, you could write a CSS rule like this:
h1 {
color: navy;
}
Here, "h1" is the selector that targets all
elements, and "color: navy;" is the declaration that styles those elements.
There are many different types of selectors that give you fine-grained control over which elements are selected. Let‘s walk through each type and see how they work.
Types of CSS Selectors
1. Universal Selector
The universal selector, denoted by an asterisk (*), selects every element on a page. It‘s rarely used on its own, but can be useful in combination with other selectors. For instance:
- {
box-sizing: border-box;
}
This rule sets the default box sizing of all elements to "border-box", a common CSS reset technique.
2. Type (or Element) Selector
A type selector targets all elements of a given HTML tag name. We saw this in the
example above. Another example is styling all links:
a {
color: blue;
text-decoration: underline;
}
Type selectors are generally used for broad, sweeping styles across a site.
3. Class Selector
Class selectors target elements based on their class attribute value. They are more specific than type selectors. A class name is preceded by a dot (.). For example:
.button {
padding: 10px;
border-radius: 5px;
}
This styles any element with a class of "button", like .
Class selectors are used heavily in CSS to apply reusable, modular styles to components.
4. ID Selector
ID selectors target a single unique element based on its ID attribute. An ID is preceded by a hash (#).
display: flex;
}
This selects the single element with an ID of "main-nav", like
a {
color: blue;
text-decoration: underline;
}
.button {
padding: 10px;
border-radius: 5px;
}
}
