Created
August 31, 2023 04:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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