0.1.2 • Published 1 year ago

@ryanmorr/scoped v0.1.2

Weekly downloads
-
License
Unlicense
Repository
github
Last release
1 year ago

scoped

Version Badge License Build Status

Scoped CSS for DOM trees

Install

Download the CJS, ESM, UMD versions or install via NPM:

npm install @ryanmorr/scoped

Usage

Import the library:

import scoped from '@ryanmorr/scoped';

Create a scoped stylesheet by providing the CSS as a string. The selectors of the CSS will be automatically converted to include a unique attribute. The styles can only take affect when an element also possesses that unique attribute. It returns a function that will apply the unique attribute to all elements of a DOM tree:

const applyStyles = scoped(`
    .foo {
        width: 100px;
        height: 100px;
    }

    .bar {
        width: 200px;
        height: 200px;
    }
`);

applyStyles(element);

You can provide the unique attribute yourself via an optional second argument:

const applyStyles = scoped(`
    div {
        color: red;
    }
`, 'scoped');

applyStyles(element);
element.hasAttribute('scoped'); //=> true

It supports all CSS selectors, properties, and at-rules, including keyframes and media queries:

const applyStyles = scoped(`
    .foo {
        background-color: red;
        animation-name: slide-in 1s ease-in;
    }

    @keyframes slide-in {
        from {
            transform: translateX(0%);
        }
        to {
            transform: translateX(100%);
        }
    }

    @media screen and (max-width: 600px) {
        .foo {
            background-color: blue;
        }
    }
`);

License

This project is dedicated to the public domain as described by the Unlicense.