Cascade
Much of how to accomplish stylings with CSS depends on the context, so it is best to understand the priniciples of the language:
- declaration
- A line of CSS that includes a property and a value.
- declaration block
- A group of declarations inside curly braces that is preceded by a selector
- ruleset | rule
- Selector plus declaration block is a ruleset or rule. Rule is less common.
- at-rule
- Rules that begin with the
@
symbol, like@import
or@media
.
/* ruleset */
selector {
/* declaration block */
property: value; /* declaration */
property: value;
}
/* Example */
body {
color: black;
font-family: Helvetica;
}
Cascade
Most of this is covered here: https://rjseymour66.github.io/docs/css/getting-started/#cascading-stylesheets
Cascade determines how conflicting rules are applied to HTML:
- CSS is simple but can get complicated as the style sheet grows, so you want to write CSS rules in a predictable way:
- CSS is added to elements depending on context: if class A exists, add B styles; if element X is a child of element Y, add Z styles.
Cascade looks at these criteria when applying rules:
- Stylesheet origin
- Browser applies user-agent styles, then User styles to override
- Author stylesheet - what the CSS dev adds to the page. Also called “User styles”
- User stylesheet - added via browser extension, usually added to overcome a11y issues
- User-agent - Browser’s default styles
- headings h1 - h6
- p tag top and bottom margins
- ol and ul styles
- link colors
- default font sizes
- Inline styles
- Can override inline styles with author
!important
rule
- Can override inline styles with author
- Layer
- Selector specificity
- Scope
- Source order
Overall order of cascade precedence
- Important user-agent
- Important user
- Important author
- Normal author
- Normal user
- Normal user-agent