Cascading Style Sheets or CSS are set up so that you can have many properties all affecting the same element. Some of those properties may conflict with one another. For example, you might set a font color of red on the paragraph tag and then later on set a font color of blue. How does the browser know which color to make the paragraphs? This is decided by the cascade.
Types of Style Sheets
There are three different types of style sheets:
- Author Style Sheets
These are style sheets created by the author of the Web page. They are what most people think of when they think of CSS style sheets.
- User Style Sheets
User style sheets are set by the user of the Web page. These allow the user to have more control over how the pages display.
- User Agent Style Sheets
These are styles that the Web browser applies to the page to help display that page. For example, in XHTML, most visual user agents display the <em> tag as italicized text. This is defined in the user agent style sheet.
Properties that are defined in each of the above style sheets are given a weight. By default, the author style sheet has the most weight, followed by the user style sheet, and finally by the user agent style sheet. The only exception to this is with the !important rule in a user style sheet. This has more weight than the author's style sheet.
To resolve conflicts, Web browsers use the following sorting order to determine which style has precedence and will be used:
- First, look for all declarations that apply to the element in question, and for the assigned media type.
- Then look at what style sheet it's coming from. As above, author style sheets come first, then user, then user agent. With !important user styles having higher precedence than author !important styles.
- The more specific a selector is, the more precedence it will get. For example, a style on "div.co p" will have a higher precedence than one just on the "p" tag.
- Finally, sort the rules by the order they were defined. Rules that are defined later in the document tree have higher precedence than those defined earlier. And rules from an imported style sheet are considered before rules directly in the style sheet.