CSS Solid

!important

!important rule overrides any other style declaration made.

Definition 2: !important rule specified style gets highest priority irrespective of default style applicable order.

Followings are default CSS styles applicable hierarchy.

  • Inline style (specified within the element using attribute).
  • Internal style sheet (specified within the STYLE element).
  • External style sheet (using link attribute, external style sheet to be attached).

Inline level style has highest priority by default and applicable to the element first.

Example: Apply styles to P elements based on default style applicable hierarchy ((!important rule is not used).

                        
<!DOCTYPE HTML>
<html>
<head>
    <title> CSS !important</title>
     <style>
         p {
             background-color:green;
             color:white;
         }
         div p {
             background-color:yellow;
             color:black;
         }
     </style>
</head>
<body>
     <p>Page level style applied</p>
     <p style="background-color:red;">Element level style applied</p>
     <p>Page level style applied</p>
      <div>
          <p>Page level style applied </p>
      </div>
</body>
</html>
                     
                     

Result:

In the above example,

  • System sets background color RED to second P element based on inline style declaration. Here inline style overrides internal styles.
  • For remaining all P elements, internal styles applied which are declared under STYLE element which is part of Header element.

Example to show how “!important” rule overrides default style hierarchy.

                        
<!DOCTYPE HTML>
<html>
<head>
    <title> CSS !important</title>
     <style>
         p {
             background-color:green !important;
             color:white;
         }
         div p {
             background-color:yellow;
             color:black;
         }
     </style>
</head>
<body>
     <p>Page level style applied</p>
     <p style="background-color:red;">Element level style applied</p>
     <p>Page level style applied</p>
      <div>
          <p>Page level style applied</p>
      </div>
</body>
</html>
                     
                     

Result:

In the above example,

  • Since “!important” rule is specified, internal style overrides inline style and sets background color GREEN to all P elements on this page.

Note:

Since “!important” rule disturbing default/natural flow, it is to be used with care.