Skip to content

Instantly share code, notes, and snippets.

@obedparla
Created July 7, 2023 13:12
Show Gist options
  • Save obedparla/dfc5a478a39a533a76c78c5fa0e987c8 to your computer and use it in GitHub Desktop.
Save obedparla/dfc5a478a39a533a76c78c5fa0e987c8 to your computer and use it in GitHub Desktop.
Turn pixel (px) values to fractional units (fr) for CSS Grid
// Turn "px" values into "fr" values.
// e.g: column widths: [768, 384, 768] and total width 1920.
// 738 / 1920 = 0.4. * 1000 = 4fr
// Times 1000 because if it's something like 10px: 10 / 1920 = 0.005
// And we want to raise it to a full integer
export function turnPxValuesToFrUnits(
fractionalValues: number[],
total: number
) {
return fractionalValues
.map(fraction => Math.round((fraction / total) * 1000))
.map(value => `${Number.isNaN(value) ? 1 : value}fr`)
.join(" ");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment