In CSS, it is possible and common to have two or more selectors that cause declarations to apply to the same element. CSS implements specific rules and algorithms to determine which rules ultimately apply to the specific element.
This is known as cascading, and is fundamental to the idea of CSS (hence why it is part of the name for the language).
The first cascading rule can be referred to as “Order” or “The Last Rule.”” Essentially, if two or more selectors are the same, than the last one will take precedence.
In the following example, the second rule overwrites the aspects duplicated in the first. (i.e. the border specification applies from the first rule, but the color and background-color specs are overwritten.)
This may seem like a funny idea right now that may lead to poorly written code. However, it is common for a developer to use pre-made CSS “frameworks” that they load in as separate documents. They may then want to customize their site by overwriting specific rules. Rather than try to change the declarations, they will create a new CSS document, that keeps track of their specific changes and rules. To ensure these rules take precedence, the developer then simply needs to load in their sheet last.
In the following example, two documents are brought in, but notice the developer’s is brought in last.
<head>
<link rel="stylesheet" href="/css/bootstrap.css">
<link rel="stylesheet" href="/css/my-custom-styles.css">
</head>
Rules which are more specific will take precedence over less specific rules. This is true even if the less specific rule is defined last.
For example;
h1 p
is more specific than p
alone..box-two
is more specific than <div>
.#first-paragraph-id
is more specific than .box-two
I like dogs.
I like dogs a lot.
I like big dogs...
If a developer believes it is necessary to force a rule, and is worried about it being overwritten, they can append the keyword !important
after the CSS property value. This tells the browser to give precedence to “this” rule.
NOTE: Be careful using the !important
keyword, as it can cause you to forget why a rule is not working when otherwise it should be. Often times, it is the use of important in another rule.
Hank Williams!