Skip to content

Instantly share code, notes, and snippets.

@easrng
Last active January 31, 2020 13:36
Show Gist options
  • Save easrng/c7f6d9062215782cef74b12183f6392b to your computer and use it in GitHub Desktop.
Save easrng/c7f6d9062215782cef74b12183f6392b to your computer and use it in GitHub Desktop.
CSS Mixins, simply. No build required, and 100% valid CSS!
[ ...document.styleSheets]
.forEach(function (css) {
if(window.cssMixinDebug) window.cssMixinStart=window.performance.now();
let myRules = css.cssRules;
let mixins = {};
let mixinSelectors = {};
for (let i of myRules) {
if (i.type === 1) {
if (i.selectorText.indexOf('[--mixin=') == 0) {
mixins[
i
.selectorText
.split('"')[1]
] = i;
} else {
let mixinsToApply = i
.style
.getPropertyValue("--mixins")
if (mixinsToApply) {
mixinsToApply = mixinsToApply.split(" ");
for (let mixin of mixinsToApply) {
mixinSelectors[mixin] = mixinSelectors[mixin] || [];
mixinSelectors[mixin].push(i.selectorText)
}
}
}
}
}
for (let mixin in mixinSelectors) {
if (mixins[mixin]) {
mixins[mixin].selectorText += ", " + (mixinSelectors[mixin].join(", "))
}
}
if(window.cssMixinDebug) window.top.postMessage((window.performance.now()-window.cssMixinStart),"*")
})
@easrng
Copy link
Author

easrng commented Jan 28, 2020

Look at a demo here

Source code for demo here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment