Skip to content

ryanmorr/scoped

Folders and files

NameName
Last commit message
Last commit date

Latest commit

a4a0a5b · Nov 17, 2024

History

29 Commits
Nov 17, 2024
Nov 17, 2024
Mar 6, 2023
Mar 6, 2023
May 22, 2020
Mar 6, 2023
May 22, 2020
May 22, 2020
Mar 6, 2023
May 22, 2020
Mar 6, 2023
Nov 17, 2024
Nov 17, 2024
Mar 6, 2023

Repository files navigation

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.