About
In a CSS stylesheet, your write several rules to define your presentation.
A rule set (also called “rule”) consists of:
- followed by a declaration block. (one of several declarations) (to apply a color for example)
Syntax
selectorList {
property: value;
[more property:value; pairs]
}
where:
- selectorList
selector[:pseudo-class] [::pseudo-element] [, more selectorlists]
Example
The CSS rule
h1 {
color: red;
font: Consolas;
}
where:
- h1 is the selector (ie an element (tag) selector)
- color: red is a declaration where:
- color is the property
- red is the property value
- {} defines the declaration block
- ; is the declaration separator
The HTML
<h1>This text will be red with the font Consolas</h1>
The result
Property Order
The property may be laid out in any order but from a reading perspective, there is properties that are more important than other.
The code guide proposes an order by type of property:
- Typographic
- Visual
- Misc
Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement. Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.
How to add programmatically a rule
To add a rule dynamically with javascript, you can just create dynamically a style element that will then add a stylesheet
Demo:
- The goal is to add dynamically the following rule:
p.steelblue { color: steelblue; }
- The javascript that adds the below css rule dynamically
let style = document.createElement("style");
style.innerText = `p.steelblue { color: steelblue; }`;
document.head.appendChild(style);
- The HTML that should be styled
<p class="steelblue">A styleblue pargraph</p>
- Output: