CSS !important
What is !important?
In CSS, a property or value can have its normal priority increased by using the !important rule.
The !important rule will actually override ALL prior styling rules for that particular property on that element if you use it!
Let’s examine an illustration:
Example
#myid {
background-color: blue;
}
.myclass {
background-color: gray;
}
p {
background-color: red !important;
}
Example Explained
In CSS, a property or value can have its normal priority increased by using the !important rule.
The !important rule will actually override ALL prior styling rules for that particular property on that element if you use it!
Important About !important
Including another !important rule is the sole way to override an existing one. crucial guideline on a declaration in the source code with the same (or greater) specificity—and this is where the trouble arises! This complicates the CSS code, making debugging challenging—especially if your style sheet is big!
We’ve made a straightforward example here. Looking at the CSS source code, it’s not entirely obvious which color is prioritized:
Example
#myid {
background-color: blue !important;
}
.myclass {
background-color: gray !important;
}
p {
background-color: red !important;
}
Advice: It’s helpful to understand the!important rule. It can be found in some CSS source code. But only use it when it’s really necessary.
Maybe One or Two Fair Uses of !important
One method of application it !important to know if there is no alternative means to override a style that needs to be overridden. This can occur if you are unable to change the CSS code when using a content management system (CMS). After that, you can make certain custom styles supersede certain CMS styles.
An further method of use !important is: Let’s say you wish to give each button on a website a unique appearance. In this instance, buttons have a gray background, white text, and border and padding:
Example
.button {
background-color: #8c8c8c;
color: white;
padding: 5px;
border: 1px solid black;
}
When a button is nested inside a more specialized element and its properties clash, it can occasionally lose its original appearance. Here’s an illustration of this:
Example
.button {
background-color: #8c8c8c;
color: white;
padding: 5px;
border: 1px solid black;
}
#myDiv a {
color: red;
background-color: yellow;
}
One way to “force” all buttons to look the same is to include the !important rule in the button’s properties, as shown below:
Example
.button {
background-color: #8c8c8c !important;
color: white !important;
padding: 5px !important;
border: 1px solid black !important;
}
#myDiv a {
color: red;
background-color: yellow;
}