utterance / utterances

:crystal_ball: A lightweight comments widget built on GitHub issues
https://utteranc.es
MIT License
8.68k stars 566 forks source link

Using relative units in CSS #588

Open brokul-dev opened 2 years ago

brokul-dev commented 2 years ago

This PR adjusts existing styles to use relative units (rem, em).

The actual behavior

Currently, the utteranc.es iframe does not respect the user's browser settings (font size). It's fixed whatever we set in the browser. That happens because of the px unit usage in stylesheets.

actual

After merge

The layout adjusts automatically to the font size setting.

after

Why are relative units preferred?

The px is an absolute unit. Using this can potentially lead to accessibility issues as we don't consider users' preferences. Also, it's worth mentioning that nowadays, many frontend frameworks such as Bootstrap prefer relative units over absolute ones.

Solution

The utteranc.es uses the Primer CSS which relies on the px unit. The idea is to still use the absolute units wrapped with SCSS helper functions that convert these values into rem and em.

The rem is a unit relative to the font size on the root element. With default browser settings (font size set to 16px) we have 1rem = 16px. To simplify calculations, we set the "font-size" property of the <html> element to 62.5%. With this in place and default browser options: 1rem = 10px so 1px = 0.1rem

The scaling.scss file contains the rem function that converts pixels to rem. For instance, rem(20px) becomes 1rem.

The suggested approach in the case of media queries is to use the em, not rem. That's because of some differences in how browsers handle this. In case of media queries 1em = default browser font size. So by default, it's 16px.

The em function in scaling.scss converts breakpoints that come from Primer CSS to em units. For example, em(32) becomes 2em.

The PR also adjusts the utteranc.es site itself, so it can be easily tested with index.html as a client. I tried not to change the existing layout, however, some minor differences are possible. In order not to break the existing design for other users I didn't touch the max-width: 760px; setting on the .utterances class. If someone wants to use relative units, then they can easily override this property on the client-side. Also, the iframe height calculation works fine.