PX or REM in CSS? Just Use REM

<p><a href="https://austingil.com/category/development/css/" rel="noopener ugc nofollow" target="_blank">CSS</a>&nbsp;has&nbsp;<a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units" rel="noopener ugc nofollow" target="_blank">a lot of different units</a>&nbsp;that you can choose from. In many cases, there is one unit that&rsquo;s clearly better than any others.</p> <p>However, one question that seems to come up throughout my career is whether you should use pixels or rems on certain properties where it doesn&rsquo;t seem to make a clear difference.</p> <p>Today I&rsquo;m going to answer that question.</p> <h1>The Setup</h1> <p>Let&rsquo;s say we have a very basic&nbsp;<a href="https://austingil.com/category/development/html/" rel="noopener ugc nofollow" target="_blank">HTML</a>&nbsp;page with two paragraphs: one sized with pixels and the other with rems:</p> <pre> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;h1&gt;PX vs. Rem&lt;/h1&gt; &lt;p style=&quot;font-size: 24px;&quot;&gt;My font size is 24px&lt;/p&gt; &lt;p style=&quot;font-size: 1.5rem;&quot;&gt;My font-size is 1.5rem&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</pre> <p>Pixels are an absolute unit, so when you set the font size to 24 pixels, it&rsquo;s going to be 24 pixels. Rems, on the other hand, are relative units that are based on the document&rsquo;s font-size. The document&rsquo;s default font size is 16 pixels, so 1.5rems x 16px is the equivalent of 24 pixels.</p> <p>The fact that rems are relative and they&rsquo;re based on a default of 16 pixels makes them harder to work with than pixels. Which is why, more often than not, I see folks using pixels. But I think it&rsquo;s a mistake.</p> <h1>The Not-so-real Problem</h1> <p>In the past, there was some confusion around how&nbsp;<a href="https://en.wikipedia.org/wiki/Retina_display" rel="noopener ugc nofollow" target="_blank">retina</a>&nbsp;or high-density displays affected pixels and&nbsp;<a href="https://en.wikipedia.org/wiki/Pixel_density" rel="noopener ugc nofollow" target="_blank">pixel density</a>. Without getting too far into it, there was a moment when pixels scaled weirdly, but that issue has since been fixed.</p> <p>And since that has been fixed, an argument I keep seeing is that is that users can scale the font size up and down by zooming the browser in or out, and both the pixel and rem sizes grow at the same rate.</p> <p><a href="https://levelup.gitconnected.com/px-or-rem-in-css-just-use-rem-470c01882021">Visit Now</a></p>
Tags: CSS PX REM