Skip to content

Instantly share code, notes, and snippets.

@adashrod
Created December 16, 2025 06:07
Show Gist options
  • Select an option

  • Save adashrod/2a646a9a723819592350d8c78605db17 to your computer and use it in GitHub Desktop.

Select an option

Save adashrod/2a646a9a723819592350d8c78605db17 to your computer and use it in GitHub Desktop.
TypeScript: check for CSS if() support
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