In this blog I am trying to explain the concept of !important rules in stylesheet.

!important Rules:

Along with the need for the cascade in CSS came the need to override it. This is where !important rules come in. The !important syntax appears within a declaration, after the property value and before the semi-colon that terminates the declaration. Two components make up this syntax; an exclamation mark, used here as a delimiter, and the important keyword. A delimiter marks the ending of the thing and the beginning of another. Here the exclamation mark singles the end of the declaration. The important keyword must appear next, followed by a semicolon to terminate the declaration;

Example code: -
1.       Enter the following markup into your text editor:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Mindstick Demo By Vijay Shukla</title>
    <style type="text/css">
        body
        {
            font: 14px sans-serif;
        }
        span#precedence
        {
            background: lightyellow;
        }
        span
        {
            background: orange !important;
        }
    </style>
</head>
<body>
    <p>
        !important rules are used to override specificity. The !important syntax causes         a selector to have<span id="precedence"> greater oprecedence than those without it.         </span>It also <span style="background: lightblue;">has greater precedence than the             (X)HTML style attribute</span>
    </p>
</body>
</html>

2.       Save the preceding document.

3.       Run the demo.

Output: -

How it works:

In this demo you see how the !important rule overrides precedence. Because the following declaration contains the !important systax, it causes the background of all the <span> elements to be orange.

span
{
     background: orange !important;
}

     

  Modified On Sep-18-2014 01:24:14 PM

Leave Comment