Skip to content

Instantly share code, notes, and snippets.

@dphiffer
Created November 3, 2011 14:10

Revisions

  1. @invalid-email-address Anonymous created this gist Nov 3, 2011.
    51 changes: 51 additions & 0 deletions important-test.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>!important considered harmful</title>
    <style>

    body {
    font: 12px verdana;
    }

    div {
    font: 10px verdana;
    color: #fff;
    width: 300px;
    height: 100px;
    padding: 20px;
    }

    p {
    width: 300px;
    }

    .normal {
    background: red;
    }

    .important {
    background: red !important;
    }

    </style>
    <script>

    // !important flag overrides JS style assignment
    window.onload = function() {
    var div = document.getElementsByTagName('div');
    div[0].style.background = 'green';
    div[1].style.background = 'green';
    };

    </script>
    </head>
    <body>
    <div class="normal">background: red;</div>
    <div class="important">background: red !important;</div>
    <p>
    This page demonstrates how setting the <code>!important</code> flag in CSS makes it impossible to override styles after the fact in JavaScript. Each div above starts with a red background, and a JavaScript onload function attempts to set each of them to green.
    </p>
    </body>
    </html>