Skip to content

Instantly share code, notes, and snippets.

@makakoa
Created August 24, 2023 20:08
Show Gist options
  • Save makakoa/66ea43d5a9c20c37a16756aad923c9e5 to your computer and use it in GitHub Desktop.
Save makakoa/66ea43d5a9c20c37a16756aad923c9e5 to your computer and use it in GitHub Desktop.
JS Style Objects to CSS Strings

Some example functions to map JS Object representations of CSS to CSS strings

inlineStylesToString stringifies flat inline style object. Eg:

inlineStylesToString({
  backgroundColor: '#fff',
  width: '100%',
  opacity: 1
}) 
// => 'background-color: #fff; width: 100%; opacity: 1; '

stylesheetObjectToString expects selectors

stylesheetObjectToString({
  button: {
    backgroundColor: '#fff',
    width: '100%',
    opacity: 1,
    '&:hover': {
      backgroundColor: '#ccc',      
    }
  }
}) 
// => 'button{background-color:#fff;width:100%;opacity:1;} button:hover{background-color:#ccc;}'

Notes:

  • For the most part these methods try not to be too smart apart from some simple quality of life considerations below
  • I added a hook to hyphenate hook to hyphenate JS properties (to allow backgroundColor instead of 'background-color'). Assumes you do not have capital letters in your properties.
  • stylesheetObjectToString tries to be a little smart to allow nested selectors and pseudo selector extensions
  • White space is added sparingly. More so to inlineStylesToString to keep the dom less cluttered.
// Inline Styles: flat object of CSS properties
function inlineStylesToString(styleObject) {
return Object.entries(styleObject).reduce((s, [property, value]) => {
return s + `${hyphenate(property)}: ${value}; `;
}, "");
}
// Stylesheet Object: CSS selectors with property objects and nested selector chaining
function stylesheetObjectToString(obj, prefix = "") {
var nested = "";
var current = Object.entries(obj).map(([key, val]) => {
if (val !== null && typeof val === "object") {
if (key.startsWith("@media")) {
nested += [key, "{", cssify(val, ""), "}"].join("");
} else {
nested += stylesheetObjectToString(
val,
key.startsWith("&") ? prefix + key.slice(1) : prefix + " " + key
);
}
return "";
}
return [hyphenate(key), ":", val, ";"].join("");
}).join("");
if (!current) return nested;
return [prefix, "{", current, "}", nested].join("");
}
// Replace any capital letter with "-<lowercase>"
function hyphenate(str) {
return str.replace(/[A-Z]/, (match) => "-" + match.toLowerCase());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment