In CSS if we have multiple rules, with the same specificity, competing for the same elements then the last declaration always wins.
This is the C, the Cascading, from the CSS acronym.
Cascading rules in the same CSS file
For example, if we have:
p { color: red };
/// other CSS rules
p { color: blue};
Then our paragraphs will be blue.
Cascading rules when importing different CSS files
This is also available when importing CSS files. If the stylesheets have conflicting rules for the same elements, the last imported rule will be applied.
// red.css
p { color: red };
// blue.css
p { color: blue };
And if we import both of these files in the same document
// index.html
<link rel="stylesheet" type="text/css" href="red.css">
<link rel="stylesheet" type="text/css" href="blue.css">
Then our paragraphs will be blue given the order of the files.
It does not matter even if we have the decoration of the CSS in the head of the HTML document. The last imported rule will win.
// index.html
<html>
<head>
<style>
p {color: red;}
</style>
<link rel="stylesheet" type="text/css" href="blue.css">
</head>
<body>
<p>This will be a blue paragraph.</p>
</body>
</html>>
Cascading rules in the same declaration block
Finally, this also applies to the actual declarations blocks of the properties. Take for example the following code:
Like in the previous examples, the paragraphs will still be blue.
p {
color: red;
font-size: 16px;
line-height: 32px;
background-color: #eee;
border: none;
color: blue;
}
By the way, because of situations like this one, it may be a good practice to have the properties declared in alphabetical order and avoid just dropping a new declaration at the end of the block.
p {
background-color: #eee;
border: none;
// conflicts are easyer to track
color: red;
color: blue;
font-size: 16px;
line-height: 32px;
}
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.