seek-oss / capsize

Flipping how we define typography in CSS.
https://seek-oss.github.io/capsize/
MIT License
1.53k stars 38 forks source link

Supporting rem as fontSize and lineheight #121

Open LukeFinch opened 1 year ago

LukeFinch commented 1 year ago

I'm looking into supporting 'rem' as a unit for our design system, and migrating away from pixel values.

Currently, if I want to do that, I have to override the outputs provided from capsize like so:

export const textCrop = ({
  lineHeight,
  fontSize,
  fontMetrics,
}: TextCropProps) => {
  const fontSizeAsNumber = parseFloat(fontSize);
  const leading = lineHeight * fontSizeAsNumber;

  const capsizeStyles = createStyleObject({
    fontSize: fontSizeAsNumber,
    leading,
    fontMetrics,
  });

  capsizeStyles.fontSize = fontSize;
  capsizeStyles.lineHeight = lineHeight.toString();
  return capsizeStyles;
};

with arguments as an example:fontSize: '2rem' lineHeight: 1.5

Looking into the source code - it seems like pixels are only needed for rounding – I assume if I wanted to use capHeight as a pixel value, and lineGap?

Is there any potential issue with me:

a) passing values in as rem - my assumption is not due to the relative nature of all the calculations b) overriding the output back to a rem unit?

andriytyurnikov commented 1 year ago

I am thinking about same thing, and I lean towards CSS calc() for font-size property, instead of compile-time computations over values normalised to px.

andriytyurnikov commented 1 year ago

@LukeFinch I've successfully reimplemended computations in CSS calc, discovered workaround is to pass values as numbers (implied rem), storing as CSS variables and to convert into units only after computation - exactly at the assignment. With this approach CSS-only rem solution is possible: https://jsbin.com/danobedoye/11/edit?html,css,output Works only in Safari (possibly due to calc() nesting limits)

smashercosmo commented 3 months ago

@andriytyurnikov I think it only works in Safari (and now also in Firefox) due to the usage of css abs() function. You can emulate abs() function by doing this:

max(var(--x), -1 * var(--x))

And it will work everywhere.

andriytyurnikov commented 3 months ago

@smashercosmo that is an interesting hypothesis, but no. CSS calc evaluation has various limits in different browsers. https://github.com/w3c/csswg-drafts/issues/3462

Replacing abs() would make nesting deeper, and would brake things.