Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active September 14, 2020 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/b4966be7c28550ff845ba9d940134d72 to your computer and use it in GitHub Desktop.
Save tomhodgins/b4966be7c28550ff845ba9d940134d72 to your computer and use it in GitHub Desktop.
Is this a worthwhile fallback to support by parsing font-size: clamp() in stylesheets? The 1000px breakpoint would probably be hard-coded
/* input */
a {
font-size: clamp(10px, 10vw, 100px);
}
/* output */
a {
font-size: clamp(10px, 10vw, 100px);
}
@supports not (font-size: clamp(1px, 2vw, 3px)) {
a {
font-size: 10px;
}
@media (min-width: 1000px) {
a {
font-size: 100px;
}
}
}
import * as parseCSS from 'https://tomhodgins.github.io/parse-css/index.js'
const stringify = (list = [], joiner = '') =>
list.map(token => token.toSource()).join(joiner)
function supportClamp(string = '') {
return parseCSS.parseAStylesheet(string).value.reduce(
(output, rule) => {
// If it's a CSS style rule
if (rule.type === 'QUALIFIED-RULE') {
const declarations = parseCSS.parseAListOfDeclarations(
stringify(rule.value.value)
)
const fontSize = declarations.filter(({name}) => name === 'font-size')
// …with a font-size property
if (fontSize.length) {
const clamp = fontSize[fontSize.length - 1].value.find(({type, name}) =>
type === 'FUNCTION'
&& name === 'clamp'
)
// …that contains a clamp() function:
if (clamp) {
const [one, two, three] = clamp
.value
.filter(({tokenType}) => tokenType === 'DIMENSION')
// …output our @supports rule.
output.push(`
@supports not (font-size: clamp(${one}, ${two}, ${three})) {
${stringify(rule.prelude)} {
font-size: ${one};
}
@media (min-width: 1000px) {
${stringify(rule.prelude)} {
font-size: ${three};
}
}
}
`.trim())
}
}
}
// Always output the original rule.
output.push(rule.toSource())
return output
},
[]
).join('\n')
}
console.log(
supportClamp('a { font-size: clamp(10px, 10vw, 100px) }')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment