Skip to content

Instantly share code, notes, and snippets.

@wingedpig
Created August 31, 2023 04:52
Show Gist options
  • Save wingedpig/5e439c3eb77affa4a6279368165805b5 to your computer and use it in GitHub Desktop.
Save wingedpig/5e439c3eb77affa4a6279368165805b5 to your computer and use it in GitHub Desktop.
A function to calculate the computed styles of elements and write them as inline styles
const attributesToInline = ['flex', 'flex-basis', 'flex-direction', 'flex-grow', 'display', 'max-width', 'max-height', 'overflow-y', 'overflow-x'];
function inlineStyles(element) {
// Get computed styles of the element
const computedStyle = window.getComputedStyle(element);
let styleString = '';
for (const attr of attributesToInline) {
const value = computedStyle.getPropertyValue(attr);
if (value) {
if ((attr == "overflow-x" || attr == "overflow-y") && value == "visible") {
continue;
}
if ((attr == "max-width" || attr == "max-height") && value == "none") {
continue;
}
if (attr == "flex" && value == "0 1 auto") {
continue;
}
if (attr == "flex-basis" && value == "auto") {
continue;
}
styleString += `${attr}: ${value}; `;
}
}
if (styleString) {
element.setAttribute('style', styleString);
}
// Loop through child elements and recursively inline their styles
for (const child of element.children) {
inlineStyles(child);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment