CSS Important Declaration
CSS ImportantIn this lesson, we will learn how and when to use the CSS !important declaration.
The !important Declaration
The !important declaration is used to give a CSS rule the highest specificity (importance), ensuring that it overrides any conflicting rules.
selector {
property: value !important;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS !important declaration Example</title>
<!-- Internal CSS -->
<style>
#para1 {
color: darkviolet;
font-size: 25px;
}
#para2 {
color: green;
font-size: 28px;
}
#para3 {
color: blue;
font-size: 22px;
}
.red-para {
color: red !important;
font-size: 30px !important;
}
</style>
</head>
<body>
<p id="para1">This is a sample paragraph</p>
<p id="para2" class="red-para">This is a sample paragraph</p>
<p id="para3">This is a sample paragraph</p>
</body>
</html>
In the above example, the id selectors has a higher specificity (importance) than class selector. So the CSS rules for color and font-size defined under the class red-para will not work on second paragraph unless you apply !important declaration to CSS values of color and font-size property of the class red-para.
When to Use !important Declaration
While !important can be a helpful tool, it should be used sparingly and in specific situations:
1. Overcoming Inline Styles
If you need to override inline styles (styles applied directly in the HTML), !important can be a solution.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS !important Example</title>
<!-- Internal CSS -->
<style>
p {
color: red !important;
font-size: 25px;
}
</style>
</head>
<body>
<p style="color: green;">This is a sample paragraph.</p>
</body>
</html>
2. Third-party CSS
When working with third-party libraries or stylesheets that you can't modify, !important can be used to ensure your custom styles take precedence.