CSS inheritance sequence
Today we will look at a very common mostly known thing in CSS – the inheritance sequence of CSS. Most of you reading this post must be aware that there are 3 ways in which you can include CSS into your web application.
- External Stylesheet
- Internal Stylesheet
- Inline Styles
External Style Sheet
An external style sheet is ideal when you are writing a style that would be applied across multiple pages. The external style sheet gives the developer lot of control over the look and feel of the entire website or web application. The external style sheet is included using the the “link” tag which is included in the head section.
<link rel=”stylesheet” href=”styles/default.css” />
Internal Style Sheet
An internal style sheet is used usually when a single document has unique style. The internal styles are written as part of the “style” tag which is again included in the “head” section.
An inline style loses many of the advantages of style sheets by mixing the content with the presentation. Inline styles should generally be avoided and be used when absolutely necessary and unavoidable!
<p style=”font-size: 20px; color: #a123bb;”></p>
As we know and/or have learned from experience, that these styles cascade into one, let’s say a “virtual” style sheet which gets applied on the entire web site/application. This cascade follows the following sequence to override each other and create one final style sheet. Number #4 in the following list has the highest priority in the cascade.
- Browser default styles
- External style sheet
- Internal style sheet
- Inline styles
So an inline styles has the highest priority, meaning that it will override a style defined inside the “head” tag, or in an external style sheet or the default browser styles. However, there are a few cases where this sequence of cascade can change!
Case #1: Usage of the !important keyword
In case there is the “!important” keyword associated with an of the styles, then that style would get applied irrespective of whether it is part of the internal or the external style sheet.
Case #3: Sequence of inclusion of stylesheets
If the link to the external style sheet is placed after the internal style sheet in the “head” tag, the external style sheet will override the internal stye sheet!
Hope you have enjoyed this post and learned a few new things. Do let me know in case you want me to include a topic as part of the blog and I would be happy to write about it! Till then keep reading and keep sharing.