CssRules — Simplify overridable CSS
Here is the full api documentation, but lets look at an example.
Example
Suppose you write a class FooBla to create an HTML element, add
functionality to it and style it minimally for it to work. The
suggested code pattern looks like:
export class FooBla {
static CSSCLASS = 'FooBla';
static CSSRULES = [
CssRule.host(...),
CssRule.detail(...),
CssRule.child(...),
];
private readonly element: HTMLElement;
constructor(cssRules: CssRules) {
this.element = cssRules.createElement('div', FooBla);
// do more with this.element
}
}
The two static variables implement the interface {@link
CssRules.CssRulesProvider}.
Instead of the constant 'FooBla' you may consider using this.name to
make sure that refactoring the class name automatically changes the
CSS class used. But some bundlers, like esbuild, potentially rename
Javascript class names. A manually crafted style sheet using
.FooBla would then no longer work.
The call to cssRules.createElement() does three things:
- It calls
document.createElementwith the given element name. - It attaches the
CSSCLASS, i.e.FooBla, to theclassListof the element. - It inserts the
CSSRULESinto the<head>element of the document if not done already.
The rules are inserted into <head> in a way that an external style
sheet using .FooBla can override these rules, see "Theory" below.
Suggestion: the rules listed as CSSRULES should be kept to the
minimum needed for the element to be operational. For example if it is
a button which does not naturally have a sufficient size for a fat
finger to hit it on a touch screen, width and height my need to be
specified. To get the element look nice, and blend with the rest of
the application, an external style sheet should be used.
Theory
Which CSS rule is applied to an element is defined by two factors:
- specificity
- declaration order
The declaration order is relevant for rules with identical specificity
only and applies to <style> elements embedded in the page and
<link> elements referencing an external style sheet. If there are two rules
p {
color: red;
}
and
p {
color: green;
}
where one appears in a <style> element and one in a CSS file referenced by
<link>, the order of the <style> and the <link> decides whether
the text will be red or green: the later one in the page wins.
- place CSS rules into a
<style>element at the front of the page<head>such that CSS files referenced with a<link>take preceedence, - create HTML elements with the right CSS class to pick up the styles.