Stop using pixel units in your CSS

Why do Web developers use “PX” units without thinking? Is it just a bad habit of theirs? Or do they lack knowledge of other CSS units? Or perhaps their design team preferred to use “PX” and “PT” as the units for the draft? So far, it’s not clear why most teams choose pixels.

Perhaps most of the reason is that it seems easier and more convenient. Intuitively, we might think we understand the unit “px” because it looks like it’s mapping our pixel screen.

The “PX” unit does make it easier to get started, but over time it reveals some problems. In this article, I will present three important reasons to avoid using pixel units. I’ll talk about the problems that use it and the solutions to those problems.

1. They are just visual reference units

Pixel units are no longer based on hardware pixels, they don’t work and look very different on many screens and resolutions. Instead, they are based on visual reference units. As a result, a more intuitive impression of these units does not exist.

Hardware is updated every day, and their pixel density is increasing. We can no longer use 96dpi as the universal pixel density for the device. 96dpi is no longer a stable reference value.

Note that if the base units are pixels, the physical units may not necessarily match the physical profile. If the reference unit is a physical unit, the pixel unit is not mapped to the entire pixel of the device. Note: If pixel units and physical units are not defined in the same way as in older versions of CSS, in particular, there is no fixed ratio between pixel units and physical units in previous versions of CSS; The physical unit is always related to the physical measurement, and the pixel unit will change most closely to the reference pixel. (This change is made because too much content is based on the 96DPI assumption that breaking this assumption would break the correctness of the content) -W3C

In summary, pixels are not reliable, and it is impossible to achieve a perfect pixel-based layout because of their unreliability.

Let’s see how many pixels are equivalent to 1mm at different DPI resolutions.

We are no longer able to identify pixels from the screen, and while we are used to this rule, we must abandon this idea. Pixels lose their meaning over time, and it’s time to stop using pixel units as the default units in CSS.

2. They are absolute values

Look at the questions raised above. Why is it wrong? Why is it impossible to achieve a perfect pixel-based layout? This is because pixel units are absolute. That means it doesn’t automatically adapt to the browser’s pixel ratio/resolution/size, etc.

If you want to satisfy a wide range of users, absolute values can’t do it! Px is not the only absolute unit. CSS has six absolute units, as shown below:

| | in inches – 1 = 2.54 cm in |

| — | — |

Cm | | 2.54 centimeters 1 cm = 96 px / |

| mm | milimeters – 1mm = 1/10(1cm)|

| pt | points – 1pt=1/72(1in)|

| pc | picas – 1pc=12pt|

| px | pixel units 1 px = 0.75 pt |

If you use these units, it means the user will see a different layout. It is not reasonable to test your pages at any resolution.

So how do we solve this problem? How to make a responsive layout? That’s right, relative units. What’s the relative unit?

“The relative unit of length means it depends on something else. It could be the font size of the parent element, or the viewport size “– MDN Web Docs

Here are the relative units we can use

| em | | element’s font size

| —- | ————————————————————— |

| the ex | font size x – height (x word high) |

| cap cap | font jealous – height (cap – height “approximately equal to the height of the Latin capital letter”) |

| ch | equivalent to character 0 (0, U + 0030) of the size. |

IC | | CJK (Chinese/Japanese/Korean), is it the size of the ideographic water (” water “, U + 6 c34) |

| | rem | of the root element font size

| | | vm viewport width is 1%

| | the vh | viewport height is 1%

| | vi inline direction for 1% of the viewport (translator note: level written language (e.g., English)) |

| vb | block 1% of the viewport (translator note: vertical written languages such as Japanese) |

| vmin | | smaller values in vw and vh

| vmax | | vw and vh larger values

You have to wonder why there are so many more relative units than absolute units.

Each of them has a specific scenario for use. Because there are so many relative units, we can solve different scenarios better. So we have to understand them deeply.

Here’s an example:

If we want to display a list, each line is up to 20 characters long. What most developers do. Calculate the average length of a character based on its font/font/size and multiply it by 20.

This method produces hard-coded pixel values. This means that if the character size changes, it has to be recalculated. This method is only an approximation and will not produce consistent results across devices.

A better solution is to use CH. You can set the column width to 20 times ch.

Here’s an example to give you a better idea.


<! DOCTYPEhtml>

<html>

    <head>

        <title>Units Playground</title>

        <meta charset="UTF-8" />

    </head>

    <body>

        <style type="text/css">

            body {

                color: white;

                text-align: center;

                box-sizing: content-box;

                margin: 1em;

            }

            #container {

                color: white;

                display: grid;

                gap: 1rem;

                grid-template-columns: max-content 1fr;

            }

            #content {

                padding: 1em;

                margin: 0;

                background-color: #5B2E48;

                color: white;

                max-width: 20ch;

            }

            #photo {

                background-color: #CEB992;

            }

        </style>

        <div id="container">

            <p id="content">

                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

            </p>

            <div id="photo">

            </div>

        </div>

    </body>

</html>

Copy the code

As you can see, we set the content’s max-width to 20ch:


#content {

 ...

 max-width: 20ch;

}

Copy the code

The above is just a small example. There are many alternatives to pixel units. If you don’t want to use relative units for layout, you can also choose Flex or Grid for layout. Remember: don’t rely on absolute units to make your layout consistent across environments, always choose to let the browser do the heavy lifting for us.

3. Accessibility: They don’t fit the user’s font size

Accessibility seems to be a topic that gets forgotten all the time. We need to pay more attention to web accessibility. Why using pixel units affects accessibility.

The default font size for the browser is 16px, but you can easily set the default font size. Correct font size is very useful for people with visual impairments. By setting the base font size of 16px, the browser hints at the font size that works best for the user.

However, when developers use absolute pixel values, the browser base values are meaningless. The default font size does not have any impact on our application. All users see the same font size. This is wrong because it ignores user preferences and damages the accessibility of the page.

How should we use the base values of fonts? By using relative units like REM and EM. What is REM/EM? Rem/EM represents the font size relative to the base font and can be applied to boxes as well as text. Simply put, the font size will eventually be several times the base font size. What’s the difference between them?

  • Rem font size relative to root.

  • Em font size relative to the element.

You can apply these units not only to font sizes, but also to other CSS elements. This means you can create an adaptive layout based on the user’s Settings. Make sure you provide the right experience for your users.

Let’s look at an example where we will adjust the layout based on the user’s base font size. In this example, we will use REM to design an adaptive layout.

<! DOCTYPE html> <html> <head> <title>Units Playground</title> <meta charset="UTF-8" /> </head> <body> <style type="text/css"> body { color: white; text-align: center; box-sizing: content-box; } h1 {font-size: 1.9rem; } h2 {font-size: 1.5rem; } p {font-size: 1.2rem; color: #5B2E48; } .main-article { padding: 1em; margin: 0; background-color: #5B2E48; color: white; width: 30em; } .sub-article { padding: 1em; margin: 0; background-color: #CEB992; color: white; margin-bottom: 1em; } </style> <article class="main-article"> <h1>Weather forecast for Barcelona</h1> <article class="sub-article"> <h2>10 May 2021</h2> <p>Cloudy</p> </article> <article class="sub-article"> <h2>11 May 2021</h2> <p>Sunny</p> </article> <article class="sub-article"> <h2>12 May 2021</h2> <p>Sunny</p> </article> </article> </body> </html>Copy the code

Note that we used REM for the padding,width, and font-size.


p {

  font-size: 1.2 rem;

  color: #5B2E48;

}

.main-article {

  padding: 1em;

  margin: 0;

  background-color: #5B2E48;

  color: white;

  width: 30em;

}

Copy the code

From the above we can see how the layout is set according to the user’s browser. When the font gets bigger, the page gets bigger. They stay in the same proportion. Although the size of the page varies from user to user, the shape remains the same.

tips

If you find that the default font size of 16px is not easy to calculate when using REM and setting the values, you can use the following tricks to simplify the calculation:

HTML {the font - size: 62.5%; /* font-size 1em = 10px */ }Copy the code

The trick here is that the default font size is 10px, so you won’t be stuck with 16px.

Final thoughts

We’ve laid out three strong reasons why pixel units should be discarded. Using relative units ensures that your layout is consistent across devices and resolutions.

Fortunately, more and more people are using REM/EM. At the same time, browsers are actively coming up with solutions. With absolute values, if the user scales, the browser scales to fit the user’s scaling. It’s not a perfect solution, it’s just an alternative.