Nyasro

CSS !important tips and Its alternative

Published: August 26, 2014

Css is very simple and straight forward language and so its "!important" attribute. I guess you guys have already known about this css attribute, it just overrides any following same css property for the same element that has already been applied.

So lets say you have following elements and class.

HTML:

<div class="parent-div" >
	<div class="child-div" >
		This is sample text
	</div>
</div>

CSS:

.child-div{
	color:green;
}
.parent-div .child-div{
	color: gray;	
}

RESULT:
This is sample text

But when you add !important attribute to .child-div css color property this will override all the following applied properties.

So,

CSS:

.child-div{
	color:green !important;
}
.parent-div .child-div{
	color: gray;	
}

RESULT:
This is sample text

Alternative to !important

Refering to previous example above, you can neglect !important attribute but still can get same effect. So, following is the alternative of !important.

CSS:

.child-div.child-div.child-div{
	color:green;
}
.parent-div .child-div{
	color: gray;	
}

And the result will be green in color.

Whenever you want to that css property to have highest priority you can repeat the class multiple times and it will overwrite all upcoming css property. This is a alternative to !important but this doesn't overwrite inline stylesheet.

Tips on using !important

From above example you know what !important attribute does. But you may not know when it will be useful or you can say the trick to use it.

So I am going to discuss about the use of !important.

You may know that the inline css property comes in first priority of the any browser to declare the property of any html element but when there comes !important attribute to any css property it overwrite previous and upcoming css propery.

Sometime, there will be javascript function that will be writing and applying css properties to element and javascript action of applying css property is always inline to element so you can not overwrite this property using external or internal stylesheets.

So, there comes a !important attribute.

No matter what javascript does to that element or apply which css property but when you apply !important attribute to any css property for that element either externally or internally, it will override the applied css properties by javascript.

This is very helpful when you dont want to go for debugging javascript and you just want simple and easy way to change or remove style for any element.

Conclusion

Using !important attribute can overwrite any inline, upcoming or dynamically appliced css properties. Whereas, repeating same class multiple times can be use as alternative to !important in some case.

If you have anything, Please comment below.