The ! important doesn't apply to body element

Tell us what’s happening:
By adding the !important after the color, it will override all other CSS styles. It can be applied to class or id, but why not onto the style for body element?

  **Your code so far**

<style>
body {
  background-color: black;
  font-family: monospace;
  color: green ;
}
#orange-text {
  color: orange ;
}
.pink-text {
  color: pink ;
}
.blue-text {
  color: blue;
}
</style>
<h1 id="orange-text" class="pink-text blue-text" style="color: white">Hello World!</h1>
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.62

Challenge: Override All Other Styles by using Important

Link to the challenge:

Why do you think !important can’t be used on body? Can you give us a code example that proves your point?

Referring the the code that I’ve attached, if I add !important after the color:green under body element, the output doesn’t change into green as I thought. Also I was tryna ask a question, not declare a statement.

It has to do with how inheritance works.

In the CSS we are styling the h1 element directly by applying an id, two classes, and an inline style. Directly targeted elements take precedence over inherited styles. The body selector is a parent element.

Directly targeted elements vs. inherited styles

Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.

First, the h1 inherits the green color from the body. That color gets overwritten by the pink color, which then gets overwritten by the blue color, which then gets overwritten by the orange color, which then gets overwritten by the white color.

white
orange
blue
pink
green

If we set !important on a property of any of the three selectors (the id and two classes) that selectors style will “win”. If we set !important on both one of the class selectors and the id selector, the id selector will win because of its higher specificity.

To make the inherited color “win” we have to explicitly set it.

<style>
  body {
    background-color: black;
    font-family: monospace;
    color: green;
  }

  h1 {
    color: inherit !important;
  }

  #orange-text {
    color: orange;
  }

  .pink-text {
    color: pink;
  }
  
  .blue-text {
    color: blue;
  }
</style>
<h1 id="orange-text" class="pink-text blue-text" style="color: white">Hello World!</h1>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.