Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active November 6, 2022 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/1d6bf6413dc4724a7739 to your computer and use it in GitHub Desktop.
Save gordonbrander/1d6bf6413dc4724a7739 to your computer and use it in GitHub Desktop.
CSS namespacing
/*
Automatically namespace all CSS selectors.
Eliminates most problems with style leak
.active {}
...becomes
.button-active {}
*/
const CLASS_SELECTOR = /\.(\w+)/;
const ID_SELECTOR = /\#(\w+)/;
const WHITESPACE = /^\s+$/;
const SELECTOR = /^[.#]/;
const prefixClasses = (css, prefix) =>
css.replace(CLASS_SELECTOR, '.' + prefix + '$1');
const prefixIds = (css, prefix) =>
css.replace(ID_SELECTOR, '#' + prefix + '$1');
export const namespace = (css, ns) =>
prefixClasses(prefixIds(css, ns), ns);
const isLineValid = (line) => WHITESPACE.test(line) || SELECTOR.test(line);
const removeExt = (path) => path.replace(/\.\w+$/, '');
const namespaceFromPath = (path) =>
removeExt(path.replace(/^\//, '').replace('/', '-')) + '-';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment