stylor
This is an ES6 module that lets you create a virtual stylesheet for a component. It takes two arguments: base
and styles
. base
is a valid CSS selector for the element to which the stylesheet will be attached. This should be unique in the document to prevent style leaks. So, best to use an id for base
. styles
is an object defining the stylesheet you want to create.
Installation
Install from npm:
npm i -g stylor
Then import it into your project. Stylor is an ES6 module, so use standard ES6 import syntax:
After importing stylor, you need to use it in a lifecycle event. For React, Preact or Inferno: componentDidMount
, for Vue: created
, Angular: ngOnInit
and Composi: componentWasCreated
. If you are using it with a library that does not have lifecycle events, use it during a DOM ready event.
Creating a Styles Object
When creating the object to define the stylesheet there are several rules to be aware of. Because this is a JavaScript object, it must follow JavaScript naming conventions. That means any CSS properties with hyphens must be converted to camel case or quoted. Any properties with non-alphabetic characters, such as :
must be quoted. An all values must be quoted.
Semicolons
Because this is a JavaScript object, you can't put semicolons at the end of a definition. Instead use a comma:
// Correct usage: // Incorrect:
Camel Case or Quoted
Below are some examples of camel case and quoted properties:
// Camel case: // Or quoted:
Pixel Values
If you're using a pixel value for a property, you can leave off the length identifier and provide just a raw number:
Nested Elements
Like LESS and SASS, you can nest child elements to define their relationship to parents. This also works for pseudo-elements.
This will produce the following stylesheet:
BEM
This will also work with BEM. When doing so, best to just use the generic body tag as the base for the stylesheet:
Joe Bodoni Ellen Vanderbilt Sam Anderson
Define BEM CSS for above markup: