Skip to content

Instantly share code, notes, and snippets.

@dphiffer
Created November 3, 2011 14:10
Show Gist options
  • Save dphiffer/1336573 to your computer and use it in GitHub Desktop.
Save dphiffer/1336573 to your computer and use it in GitHub Desktop.
CSS !important flag considered harmful
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment