search
HomeWeb Front-endCSS TutorialThe evolution and application of CSS layout units: from pixels to relative units based on the font size of the root element

The evolution and application of CSS layout units: from pixels to relative units based on the font size of the root element

From px to rem: The evolution and application of CSS layout units

Introduction:
In front-end development, we often need to use CSS to implement page layout . Over the past few years, CSS layout units have evolved and developed. Initially we used pixels (px) as the unit to set the size and position of elements. However, with the rise of responsive design and the popularity of mobile devices, pixel units have gradually exposed some problems. In order to solve these problems, the new unit rem came into being and was gradually widely used in CSS layout.

1. Limitations of the pixel unit (px)
1.1 Fixed size
As the earliest widely used unit, the pixel unit has the characteristic of fixed size in layout. This means that when the page is displayed on different devices or different screen sizes, the size of the pixel unit will not adapt, causing the page layout to be disordered or unable to be displayed completely.

1.2 High-resolution device issues
With the popularity of high-resolution devices, such as Retina screens, the shortcomings of pixel units are more obvious. When elements with low pixel unit settings are displayed on a high-resolution device, it will cause pixelation or blurry display, affecting the user experience.

1.3 Complex editing
The pixel unit needs to be adjusted according to the resolution of the device, which means that the pixel density of different devices needs to be considered when writing CSS, which increases the complexity of writing and maintaining code.

2. Introduction to rem unit
2.1 What is rem
rem is a relative unit, which represents the unit of font size relative to the root element (html). Its size is relative to the font size of the root element. When we set the font size of the root element to 16px, 1rem equals 16px.

2.2 Advantages of rem

  • Adaptive layout: Using rem units can be adaptively adjusted according to the font size of the root element, thereby achieving flexible layout changes on different devices.
  • Solving the problem of high-resolution devices: Since rem is a relative unit and is not affected by the pixel density of the device, consistent layout effects can be achieved at different resolutions.
  • Simplify code writing: Using rem units can simplify code writing, and you no longer need to consider the pixel density of different devices.

3. How to use rem units
3.1 Set the font size of the root element
Before using the rem unit, you need to set the font size of the root element first. Normally, we will set the font size of the root element to 16px, that is, 1rem=16px.

html {
  font-size: 16px;
}

3.2 Using rem units
Once the font size of the root element is set, you can use rem units for layout in other elements.

.container {
  width: 20rem; /* 相当于320px */
  height: 10rem; /* 相当于160px */
  font-size: 1.2rem; /* 相当于19.2px */
  margin-top: 2rem; /* 相当于32px */
}

4. Dynamically change the font size of the root element
4.1 Media query
Through media query, you can dynamically change the font size of the root element according to different screen sizes.

@media screen and (max-width: 768px) {
  html {
    font-size: 14px;
  }
}

@media screen and (min-width: 768px) {
  html {
    font-size: 16px;
  }
}

@media screen and (min-width: 1024px) {
  html {
    font-size: 18px;
  }
}

4.2 JavaScript dynamic calculation
Use JavaScript to dynamically calculate the font size of the root element based on the screen size.

function setRootFontSize() {
  var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
  var fontSize = screenWidth / 10;
  document.documentElement.style.fontSize = fontSize + 'px';
}

setRootFontSize();

window.addEventListener('resize', setRootFontSize);

5. Summary
By using rem units, we can implement responsive layout and solve layout problems on different devices. Using rem units can make our layout more flexible and adaptive, while simplifying code writing. In actual projects, we should choose appropriate layout units according to actual needs and use rem units rationally to achieve a better user experience.

References:

  • https://developer.mozilla.org/zh-CN/docs/Web/CSS/font-size
  • https:/ /www.w3schools.com/cssref/css_units.asp
  • https://juejin.cn/post/6844904117648772110

The above is the detailed content of The evolution and application of CSS layout units: from pixels to relative units based on the font size of the root element. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

Revisiting Image MapsRevisiting Image MapsMay 07, 2025 am 09:40 AM

Let’s run through a quick refresher. Image maps date all the way back to HTML 3.2, where, first, server-side maps and then client-side maps defined clickable regions over an image using map and area elements.

State of Devs: A Survey for Every DeveloperState of Devs: A Survey for Every DeveloperMay 07, 2025 am 09:30 AM

The State of Devs survey is now open to participation, and unlike previous surveys it covers everything except code: career, workplace, but also health, hobbies, and more. 

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft