Created
December 16, 2025 06:07
-
-
Save adashrod/2a646a9a723819592350d8c78605db17 to your computer and use it in GitHub Desktop.
TypeScript: check for CSS if() support
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 CSS_NO_IF_SUPPORT = /body\s*\{\s*\}/; | |
| /** | |
| * Checks if the browser supports CSS if(). | |
| * @returns true if the browser supports CSS if(), false otherwise | |
| */ | |
| export function supportsCssIf(): boolean { | |
| if (typeof document === "undefined") { | |
| return false; | |
| } | |
| const style = document.createElement("style"); | |
| style.textContent = ` | |
| body { | |
| background: if(media(screen): red); | |
| } | |
| `; | |
| document.head.append(style); | |
| /* | |
| * In browsers that support if(), cssText will include the background property with the if statement, | |
| * else, it will just be `body { }`. | |
| */ | |
| const matchesEmpty = CSS_NO_IF_SUPPORT.test(style.sheet?.cssRules[0].cssText ?? ""); | |
| style.remove(); | |
| return !matchesEmpty; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment