Last Rule
Exercise
- In the "index.html" file, replace the code with the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS</title> <link rel="stylesheet" href="./css/styles.css"> </head> <body> <div> <h1>Section 1</h1> <p>This is the first paragraph of section 1</p> </div> <div> <h1>Section 2</h1> <p>This is the first paragraph of section 2</p> </div> </body> </html>
- Save.
- If "Live Server" is not already running, right-click anywhere in the editor and select "Open with Live Server" from the context menu.
- In the "styles.css" file, replace the code with the following:
body { color: blue; } h1 { color: green; } body { color: red; }
- Save.
- In the browser, you should see the following:
Code Walkthrough and Explanation
The "last rule" in CSS refers to the last CSS rule that Is defined for a specific HTML element. In CSS, the rules are applied to the elements in the order they appear in the stylesheet. The last rule that is defined for a specific element will take precedence over all previous rules and will be applied to the element unless it is overridden by another rule with higher specificity. This is known as the cascading nature of CSS where styles are cascaded down the element hierarchy and the last defined rule has the highest priority. So when multiple rules are defined for the same element, the last rule will be applied to the element and the styles defined in earlier rules will be ignored.
In the example, there were two CSS rule sets defined for the <body>
element, one at the top
of the
CSS file and one at the bottom. The bottom one defined the color again but as red and so this rule had higher
priority
based on the "last rule".
Experiment with the Code
- Try adding another
h1
selector to thecss
and making the color blue.
Video and Code References
Questions? Subscribe and ask in the video comments: