@haraldki/cssrules

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 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:

  1. It calls document.createElement with the given element name.
  2. It attaches the CSSCLASS, i.e. FooBla, to the classList of the element.
  3. It inserts the CSSRULES into 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.

Generated using TypeDoc