freeCodeCamp Challenge Guide: Override Class Declarations by Styling ID Attributes

Override Class Declarations by Styling ID Attributes


Problem Explanation

In order to understand overriding in CSS, you must first understand the principle of precendence in CSS.

The key rule to remember is that CSS is read from the bottom to top.

An example of this is:

<style>
  body {
    background-color: black;
    font-family: Arial;
    color: black;
  }
  .red-text {
    color: red;
  }
  .blue-text {
    color: blue;
  }
</style>
<h1 class="red-text blue-text">Example</h1>

In the example above, the text Example will be in blue because the last added class was blue-text.

It is key to remember that an id attribute will take precedence over classes, meaning that it ranks highest.

You can create an id attribute by adding the # before the name of the class, like below:

<style>
  #purple-text {
    color: purple;
  }
</style>

Here is an example to show you how to Override Class Declarations by Styling ID Attributes:

<style>
  body {
    background-color: black;
    font-family: Arial;
    color: black;
  }
  .red-text {
    color: red;
  }
  .blue-text {
    color: blue;
  }
  #green-color {
    color: green;
  }
</style>
<h1 id="green-color" class="red-text blue-text">Example</h1>

This will make the text Example be green because the id attribute will always take precedence over class declarations.

10 Likes
body { background-color: black; font-family: Monospace; color: green; } .pink-text { color: pink; } .blue-text { color: blue; } #orange-text { color: orange; }
6 Likes