CSS – Cascading Order

Today I want to talk about the cascading order for different styles applied to the same web element(html tag) on your page. Sometimes it can be frustrating when you try to apply a style; you have the correct selector in your style sheet but for some reason it’s not overriding the current style already applied.

There is a reason for that, cascading precedence:

Preceding styles are overridden by Proceeding styles

Back to Basics

For instance lets take a paragraph style that being applied by default to all the paragraph tags:

HTML:

	<p class="style-one style-two">What cascading order was used?</p>


CSS:

p
{
	font-family: Georgia, "Times New Roman", Times, serif;
	font-size:24px;
	color:white
}

2013-03-30_004010

We want to override this style, lets make the text aqua:

p
{
        ...
	color:white
}

p.style-one
{
	color:Aqua
}

2013-03-30_003930

We want to override this tag yet again, let’s make it orange:

p
{
        ...
	color:white
}

p.style-one
{
	color:Aqua
}

p.style-two
{
	color:Orange
}

2013-03-30_004734

As you can see, we are overriding our styles nicely. You probably would have noticed that in the html markup:

	<p class="style-one style-two">What cascading order was used?</p>

We have defined style-one and style-two. The order of these classes in the html does not affect the ordering of the style being applied:

	<p class="style-two style-one">What cascading order was used?</p>

This will render the same result:

2013-03-30_004734

Cascading Styles

Changing the order of the class applied in html markup makes no difference to css precedence. What if we change the order in the css stylesheet itself?

p
{
        ...
	color:white
}

<!-- We have moved p.style-two above p.style-one -->

p.style-two
{
	color:Orange
}

p.style-one
{
	color:Aqua
}

2013-03-30_003930

The preceding style style-two has been overridden by style-one just as expected, it has cascaded.

Overriding the over-rider (!important)

We can however override this cascading rule by using the !important declaration. So no matter the order of the styles in the stylesheet, the style with !important will be honoured:

p
{
        ...
	color:white
}

<!-- We have moved p.style-two above p.style-one -->

p.style-two
{
	color:Orange!important
}

p.style-one
{
	color:Aqua
}

2013-03-30_004734

This covers the basic fundamentals of cascading styles within your stylesheet. In the next couple of days I will be covering External CSS vs Internal CSS vs Inline CSS and then finally CSS specificity.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.