Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Last active October 17, 2018 11:38
Show Gist options
  • Save audunolsen/9af887ab8a4b212aff8e5f63111b6d67 to your computer and use it in GitHub Desktop.
Save audunolsen/9af887ab8a4b212aff8e5f63111b6d67 to your computer and use it in GitHub Desktop.
A method I defined on the CSSStyleDeclaration API prototype object for setting multiple properties at once
CSSStyleDeclaration.prototype.setProps = function(props) {
for (const prop in props) this.setProperty(prop, props[prop]);
}
/*
CONTEXT:
I'm usually not a proponent of setting styles through js, but I've recently
discovered that you can modify CSS variables with JS, which is YUUGE.
I therefore added a super simple method to the CSSStyleDeclarations API
so I can set multiple properties at once.
*/
/*
Usage example: Let's say you need a grid which only has the
amount of rows which actually fit the initial window height.
———
Global variables can stay neatly organized in our root for easy JS access
*/
:root {
--rows: 0;
--row-height: 0;
}
body {
display: grid;
grid-template-rows: repeat(var(--rows), var(--row-height));
}
/*
Usage example: Let's say you need a grid which only has the
amount of rows which actually fit the initial window height.
———
Let's update both variables thanks to our extend
of CSSStyleDeclaration. Yay for less ad hoc shit code.
*/
let gridSize = { row: 200 }
const root = document.documentElement;
root.style.setProps({
"--rows" : Math.floor(window.innerHeight / gridSize.row),
"--row-height" : gridSize.row + "px"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment