Member-only story
Mastering CSS Selectors: A Beginner’s Guide to Combining and Targeting Elements
Decoding Multiple CSS Selectors: How Browsers Interpret Your Styles
When you have multiple CSS selectors in your stylesheet, the browser reads them from top to bottom, applying styles to the targeted elements as it goes. If a later selector targets the same element as an earlier one, the later style will override the earlier style, unless the earlier style has higher specificity.
p {
color: blue;
}
p {
color: red;
}
In this case, all paragraphs (<p>
elements) will be styled with red text, because the second p
selector comes after the first one and overrides the blue color.
Combining Selectors: From General to Specific
There are several ways to combine CSS selectors to target elements more precisely. Here are some common methods, ordered from the most general to the most specific:
Comma-separated selectors
This method allows you to apply the same style to multiple elements. For example:
h1, h2, h3 {
font-family: Arial, sans-serif;
}