DEV Community

loading...
Cover image for Precedence Rules in CSS3-P1

Precedence Rules in CSS3-P1

rohinibali profile image Rohini Bali ・2 min read

While styling a single HTML document via cascading style sheets one has to keep in mind the CSS Precedence rule which I used to often get confused with. So let's begin.
We all know that there are typically three ways to style an HTML document. For those who don't know let me tell you that these are:

1.By Embedding the CSS inside the style attribute of the HTML elements i.e., in the start tag itself.

embedded style attribute within html

2.By Embedding CSS inside style HTML element i.e., within the style tag.

Alt Text

3.By linking the External CSS files in the HTML within the head tag.

Alt Text

Now the question that arises is what if someone does styling of a single html page using all the methods mentioned above? This is an obvious question that comes to beginner's mind when they get into web development.
Let's Understand how CSS Precedence rules resolve this by this example here:

Alt Text

Did you see what happened here? We have declared the colour for h1 in style tag, in CSS stylesheet which is linked in the head and also within the h1 tag as an attribute. The precedence in CSS works like this :

a) If nothing is specified for a particular tag, each browser has its own rendering properties which are predefined within them, which is what we usually see when we open a simple HTML document in our browsers.

Alt Text
Look carefully we have not linked any stylesheet in the html file.

b) The browser while rendering the HTML document checks within the head tag for linked stylesheets and if there is one present it will display the contents as prescribed in the stylesheet.

Alt Text

c) The then proceeds to check for the style tag and the content within the style tag to make the particular changes

Alt Text

d) Finally the browser looks for style contents within the particular tag itself which in our case is h1.As we all can see it has overridden all the other style tag and stylesheet linked with the html.

Alt Text

TO BE CONTINUED...

Discussion (1)

pic
Editor guide
Collapse
rajatmehra05 profile image
RAJAT MEHRA

Nice 👍