Introduction to PX, EM, and REM Differences
Category Programming Technology
PX
px stands for pixel, a relative length unit. The pixel px is relative to the resolution of the display screen.
PX Characteristics
- IE cannot adjust font sizes set in px;
- Most foreign websites can be adjusted because they use em or rem as font units;
- Firefox can adjust px, em, and rem, but over 96% of Chinese internet users use IE (or its kernel).
EM
em is a relative length unit. It is relative to the font size of the current object's text. If the inline text's font size is not manually set, it defaults to the browser's default font size.
EM Characteristics
- The value of em is not fixed;
- em inherits the font size of the parent element.
Note: The default font height in any browser is 16px. All unadjusted browsers conform to: 1em = 16px. Therefore, 12px = 0.75em, 10px = 0.625em. To simplify the conversion of font-size, declare Font-size = 62.5% in the CSS body selector, which makes the em value 16px * 62.5% = 10px. Thus, 12px = 1.2em, 10px = 1em. Simply divide your original px value by 10 and replace it with em.
When writing CSS, pay attention to:
- Declare Font-size = 62.5% in the body selector;
- Divide your original px value by 10 and replace it with em;
- Recalculate the em values of enlarged fonts to avoid repeated font size declarations.
Avoid the phenomenon of 1.2 * 1.2 = 1.44. For example, if you declare a font size of 1.2em in #content, then the font size for p should be 1em, not 1.2em, because this em is not the same as the other em; it has inherited the font height from #content, making 1em = 12px.
REM
rem is a new relative unit (root em) introduced in CSS3, which has gained widespread attention. What is the difference between rem and em? The difference is that when setting font sizes with rem, it is still relative but only to the HTML root element. This unit combines the advantages of relative and absolute sizes. It allows for proportional adjustments of all font sizes by modifying just the root element and avoids the cascading effects of nested font sizes. Currently, all browsers except IE8 and earlier versions support rem. For browsers that do not support it, a simple workaround is to add an absolute unit declaration. These browsers will ignore the font size set with rem. Here is an example:
p {font-size:14px; font-size:.875rem;}
Note: The choice of font units depends on your project. If your users are on the latest browsers, rem is recommended. For compatibility, use px, or both.
Choosing between px and rem?
For sites that need to adapt to only a few mobile devices with minimal resolution impact, px is sufficient.
For sites that need to adapt to various mobile devices, use rem, such as devices with significant resolution differences like iPhones and iPads.
** Click to Share Notes
-
-
-