- Stop Using the Pixel Unit in CSS
- By Jose Granja
- Translation from: The Gold Project
- This article is permalink: github.com/xitu/gold-m…
- Translator: Hoarfroster
- Proofreader: KimYangOfCat, Kimhooo
Why do Web developers use PX units so blindly? Is it just a bad habit? Is it because of a lack of knowledge in other units? Maybe it’s because the design team’s simulation relies on PX and PT? It’s not clear why pixels are currently the preferred unit for most teams.
Perhaps the main reason is that it looks simple and convenient. Intuitively, we think we know this unit because it looks like it’s mapping a pixel screen.
Px units are easy to use, but then they become a problem. In this article, I’ll cover three of the most powerful reasons to avoid pixel units. We will discuss the problems with its use and some possible solutions.
1. They are optical reference units only
Pixel values are no longer based on hardware pixels, they don’t work on many screens and resolutions, and they all look very different. They are only based on optical units, so we find that the more intuitive part of the unit no longer exists.
The hardware is changing every day and the pixel density is growing. We cannot rely on the assumption that the device has a pixel density of 96dpi — this is no longer a stable reference value.
“Please note that if the anchor point units are pixel units, the physical units may not match their physical size. Or, if the anchor point unit is a physical unit, the pixel unit may not map to the total number of device pixels.
Note that pixel units and physical units are defined differently from earlier versions of CSS. In particular, in earlier versions of CSS, pixel units and physical units were not associated in fixed ratios: the physical units were always associated with the physical size, and the pixel units changed to most closely match the reference pixels. (This change was made because the amount of existing content depends on 96DPI assumptions, and breaking that assumption breaks the content.) “– [W3C] (www.w3.org/TR/2011/WD-… /)
In short, this means pixels are unreliable. Due to their unreliable nature, pixel-perfect layouts may not be possible.
Let’s look at the different pixels per inch equivalent to 1mm pixels:
Gone are the days when you could tell pixels apart on a screen. We’re used to this kind of limitation, and it’s an idea we need to let go of. Over time, the meaning of the word “pixel” has lost its meaning, and it’s time to stop making it the default unit in our CSS code.
2. They are absolute values
Looking at the question above, why does it happen? Why can’t our layouts achieve pixel perfection? Because the pixel unit is absolute. This means it won’t be able to accommodate our browser’s pixel ratio, resolution, size, etc.
Absolute values are usually not very useful if you want to meet the needs of a large audience. Is px the only absolute unit? No, there are six other absolute units in CSS, as shown below:
This means that if you use these units, visitors to your site will see a variety of layouts, and it would be unreasonable to allow your page to be adapted to any possible resolution.
How can we solve this problem? How can we make the layout responsive? — Use relative units. What the hell is that?
“The unit of relative length is relative to another unit, perhaps the font size of the parent element or viewport size.” – [MDN Web Documentation] (developer.mozilla.org/zh-CN/docs/…
Let’s examine the relative units we can use:
You’ll see that the list of relative units is larger than the list of absolute units. Why are there so many relative units?
Each of these has a specific solution that is more suitable for use. It’s good news that there are so many options, because we know we can cover so many different use cases. That’s why it’s important to understand each of them.
Suppose we want to display a column of up to 20 characters per line.
What do most developers want? Measure the average length of a character by its font, font, size, and thickness and multiply it by 20.
This method causes us to need a hard-coded pixel value, which also means that if the font size changes, you’ll have to do the calculation again. This approach is only an approximation and does not work consistently on all devices.
What’s a better solution? Use the ch unit. You can base the target column width on a multiple of the ch unit
Let’s take a look at the code to better understand this:
<! 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 have limited the max-width of our content to 20ch.
#content {
max-width: 20ch;
}
Copy the code
These are just examples. There are many alternatives to pixel units. Sometimes, you don’t need relative units. You can use flex and Grid layout to adjust the layout accordingly. Not relying on absolute units allows you to keep your layout consistent. Remember, always rely on the browser to do the heavy lifting first.
3. Accessibility: They don’t fit the user’s default font size
Accessibility is a forgotten topic that we should all pay more attention to. How does the use of pixel units affect accessibility?
The browser lets you configure the default base font size. By default, it is set to 16px, but can be easily changed. This is very useful for visually impaired people. The browser then prompts us about the preferred user’s font size by setting the base font size to this value.
However, if the developer uses absolute pixel values, this information is ignored. The basic “font size” has no effect on the layout of our application. All users will have the same font size. This is a bad thing because you ignore user preferences and compromise the accessibility of the page.
How do we respect the base font size? By using relative units such as REM and EM. What are REM and EM? The REM and EM units represent the font size (from box to text) relative to the base font. In short, this means that your text font size will be a multiple of the user’s preferred font size. What’s the difference?
rem
The size of the root element (:root
)font-size
Decision.em
The size of the parent elementfont-size
Decision.
You are not limited to using these units only for the font-size property. They can be used anywhere in a CSS element. This means that you can create adaptive layouts based on user Settings. You can make sure you’re providing the right experience for your users.
Let’s look at an example where we adjust the entire layout based on the user’s base font size. For this particular example, we will rely on REM to design an adaptive layout:
<! 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;
}
h1 {
font-size: 1.9 rem;
}
h2 {
font-size: 1.5 rem;
}
p {
font-size: 1.2 rem;
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
Notice that WE have applied REM to the PADDING, width, and font-size properties.
p {
font-size: 1.2 rem;
color: #5B2E48;
}
.main-article {
padding: 1em;
margin: 0;
background-color: #5B2E48;
color: white;
width: 30em;
}
Copy the code
You can see at the top how the layout ADAPTS to the user’s browser Settings. Fonts are bigger, but articles are also bigger — they’re bigger to preserve proportions. Even though they are different sizes for different users, they remain the same shape.
Bonus tip
When using REM and REM units, it can be cumbersome to use the default base font of 16px to express everything. In this case, there is a very popular technique:
html {
font-size: 62.5%; /* Set font size 1em = 10px */ based on the default browser font size
}
Copy the code
Using this trick, all font sizes will now be a 10px factor based on the default pixel of 16px. It makes your code a little less cluttered without compromising accessibility. It will make your job easier.
Final thoughts
We have seen three strong reasons why we should abandon the pixel unit. Relying on relative units or layout features will ensure that your layout is consistent across devices and resolutions.
Fortunately, the use of relative units such as REM and EM is expanding. In the meantime, browsers are trying to offer some solutions. When using absolute values, if the user is scaling, the browser unit will scale to match the appropriate scaling applied by the user. It’s not a perfect experience, but it’s a good backup.
I hope this article has given you the final push to get as far away from pixels as possible.
If you find any errors in the translation or other areas that need improvement, you are welcome to revise and PR the translation in the Gold Translation program, and you can also get corresponding bonus points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.