css-scoping
v1.0.4
Published
Scope CSS selectors with a custom class name.
Readme
CSS Scoping
CSS Scoping is a utility function that automatically prepends a given class name to a given CSS string, making it easier to encapsulate styles and avoid conflicts across external styles.
How it works
The core function takes a CSS string and prepends a given block class to selectors, except for global selectors such as html, body, and :root. This helps ensure that styles are applied only within the intended scope.
Installation
Clone the repository and import the function into your project:
npm install css-scopingParameters
- css (
string): The raw CSS code to be scoped. - blockClass (
string): The class name to prepend to selectors for scoping (e.g.,.my-component). - globalSelectors (
string[], optional): Selectors that should not be scoped (default:['html', 'body', ':root']).
Usage example
import scopeCss from './index.js';
const css = `
.button {
color: red;
}
html, body {
margin: 0;
}
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}
`;
const scoped = scopeCss(css, '.my-block');
console.log(scoped);Output:
.my-block .button {
color: red;
}
html, body {
margin: 0;
}
@keyframes fade {
from { opacity: 0; }
to { opacity: 1; }
}License
MIT
