To go further
Specificity
Specificity is the order by which the browser decides which CSS styles will be displayed. A best practice in CSS is to style elements while using the lowest degree of specificity so that if an element needs a new style, it is easy to override.
Important
IDs are the most specific selector in CSS, followed by classes, and finally, type.
To make styles easy to edit, it’s best to style with a type selector, if possible. If not, add a class selector. If that is not specific enough, then consider using an ID selector.
Chaining
When writing CSS rules, it’s possible to require an HTML element to have two or more CSS selectors at the same time.
This is done by combining multiple selectors, which we will refer to as chaining. For instance, if there was a special class for <h1>
elements, the CSS would look like below:
The code above would select only the <h1>
elements with a class of special. If a <p>
element also had a class of special, the rule in the example would not style the paragraph.
Chaining and Specificity
Adding more than one tag, class, or ID to a CSS selector increases the specificity of the CSS selector. For instance, consider the following CSS:
Both of these CSS rules define what a <p>
element should look like. Since .main p
has a class and a p
type as its selector, only the <p>
elements inside the .main
element will appear red.
This occurs despite there being another more general rule that states <p>
elements should be blue.
Descendant Combinator
In addition to chaining selectors to select elements, CSS also supports selecting elements that are nested within other HTML elements, also known as descendants. For instance, consider the following HTML:
The nested <li>
elements are descendants of the <ul>
element and can be selected with the descendant combinator like so:
In the example above, .main-list
selects the element with the .main-list
class (the <ul>
element). The descendant <li>‘s
are selected by adding li
to the selector, separated by a space.
This results in .main-list li
as the final selector.
Multiple Selectors
In order to make CSS more concise, it’s possible to add CSS styles to multiple CSS selectors all at once. This prevents writing repetitive code. For instance, the following code has repetitive style attributes:
Instead of writing font-family: Georgia
twice for two selectors, we can separate the selectors by a comma to apply the same style to both, like this:
By separating the CSS selectors with a comma, both the <h1>
elements and the elements with the menu class will receive the font-family: Georgia
styling.