Example of using rem to replace px in vue project

Example of using rem to replace px in vue project

Mobile page adaptation, rem and vw adaptation solutions

Basic point: rem is relative to the root node font size. So no need for px;
Root font: font size in px;
px: Just think of it as cm (centimeter);
Benchmark: 750 design drafts (generally UI designers give 750 design drafts);

tool

vue-cli: Use scaffolding to build vue front-end projects
postcss: postcss is a tool that uses js plug-ins to help you convert CSS styles. For example, here we replace 16px in your file with 1rem (the root size defaults to 16px); this way you don’t have to calculate it yourself!
cssrem: mainly helps you convert px (px on the UI design draft) into corresponding rem
Then: you also need to use js code to dynamically calculate the font size that the root directory should have. Anyway, it is just a piece of js code to dynamically get the screen width

Install the plugin

npm i postcss, postcss-pxtorem, postcss-loader, postcss-import, postcss-url

Then add it to index.html

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Add a .postcssrc.js file to the project root directory

module.exports = {
    "plugins": {
      "postcss-import": {}, //Used for @import to import CSS files"postcss-url": {}, //Path to introduce CSS files or node_modules files"postcss-aspect-ratio-mini": {}, //Used to process the aspect ratio of element containers"postcss-write-svg": { utf8: false }, //Used to process the 1px solution for mobile terminals. This plug-in mainly uses border-image and background to do 1px related processing.
      "postcss-cssnext": {}, //This plug-in allows us to use future features of CSS, and it will do relevant compatibility processing for these features.
      "postcss-px-to-viewport": { //Convert px units to viewport units such as vw, vh, vmin or vmax. It is also one of the core plug-ins of the vw adaptation solution.
          viewportWidth: 750, //Width of the viewportviewportHeight: 1334, //Height of the viewportunitPrecision: 3, //The number of decimal places to convert px to the viewport unit valueviewportUnit: 'vw', //Specify the viewport unit value to be convertedselectorBlackList: ['.ignore', '.hairlines'], //Specify the class that does not convert the viewport unit value, which can be customized and added infinitelyminPixelValue: 1, //Less than or equal to 1px is not converted to the viewport unitmediaQuery: false //Allow px in media queries
      },
      "postcss-viewport-units":{}, //Adapt vw, vh, vmin and vmax. This is an essential plugin for implementing vw layout. "cssnano": { //Mainly used to compress and clean up CSS code. In Webpack, cssnano is bundled with css-loader, so there is no need to load it yourself.
          preset: "advanced", //Repeat autoprefixer: false, //Both cssnext and cssnano have autoprefixer. In fact, only one is needed, so delete the default autoprefixer and set the autoprefixer in cssnano to false.
          "postcss-zindex": false //As long as this plugin is enabled, the z-index value will be reset to 1
       } 
    }
  } 

When you switch to different screen sizes, you need to dynamically change the root font size. Insert a simple js into the head: create a new shipei.js in the public directory, and then introduce this js into the head of index.html

//shipei.js
(function() {
   function autoRootFontSize() {
       document.documentElement.style.fontSize = Math.min(screen.width,document.documentElement.getBoundingClientRect().width) / 750 * 32 + 'px';
         // Take the minimum value of screen.width and document.documentElement.getBoundingClientRect().width; divide by 750, multiply by 32; if you understand, it is 32px of the original size of 750; if the screen size becomes 375px, then the font size will be 16px; that is, the root fontSize size changes in direct proportion to the screen size! Isn't it simple?}
   window.addEventListener('resize', autoRootFontSize);
   autoRootFontSize();
})();

index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/public.css" rel="external nofollow" type="text/css">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" rel="external nofollow" >
    <title><%= htmlWebpackPlugin.options.title %></title>
    <script src="/shipei.js" type="text/javascript" charset="utf-8"></script>
  </head>
  <body>
    
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

Note that you don't need to write the beginning directory for things placed in public. When the scaffolding is packaged, it will look for it in the public folder.

about

getBoundingClientRect().width actually gets the distance between the right side of the parent and the browser origin (0,0) and the left side of the parent, that is, the width of the parent + 2padding + 2border.
At this time, clientWidth is equal to the width of the parent + 2*padding, excluding the width of the border.
When the child content is not hidden, that is, overflow is auto, the width of the former remains this number because the parent does not adapt the box model. The width of the latter is the width obtained above minus the width of the scroll bar (17px);

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            *{
                margin: 0;
                padding: 0;
            }
        </style>
    </head>
    <body>
        <div id="divParent" style="background-color: #aaa; padding:8px; border:solid 7px #000; height:200px; width:500px; overflow:hidden;">
                <div id="divDisplay" style="background-color: #0f0; margin: 30px; padding: 10px;
                    height: 400px; width: 600px; border: solid 3px #f00;">
                </div>
            </div>
    </body>
</html>
<script type="text/javascript">
    /* 
     getBoundingClientRect().width actually gets the distance between the right side of the parent and the browser origin (0,0) and the left side of the parent, that is, the width of the parent + 2padding + 2border.
     At this time, clientWidth is equal to the width of the parent + 2*padding, excluding the width of the border.
     When the child content is not hidden, that is, overflow is auto, the width of the former remains this number because the parent does not adapt the box model. The width of the latter is the width obtained above minus the width of the scroll bar (17px); the example is as follows:
     */
     var divP = document.getElementById('divParent');
            var divD = document.getElementById('divDisplay');
    
            var clientWidth = divP.clientWidth;
            var getWidth = divP.getBoundingClientRect().width;
            divD.innerHTML += 'clientWidth: ' + clientWidth + '<br/>';
            divD.innerHTML += 'getWidth: ' + getWidth + '<br/>';
</script>

The result is clientWidth is 516, which is calculated as content width + 2padding.
getWidth (that is, getBoundingClientRect().width) includes content width + 2padding + 2border
Step 5: Convert the px on the design draft into rem units: Install the cssrem plug-in (in the plug-in market):
Then go to File-->Preferences-->Settings and search for cssrem and set the Root Font Size to 16.

This is the end of this article about the implementation example of using rem to replace px in vue projects. For more relevant vue rem to replace px content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • About the issue of vue using postcss-pxtorem for mobile adaptation
  • Specific method of using postcss-pxtorem in vue3.0
  • Detailed explanation of the problems encountered when using px2rem in Vue-cli3.X
  • Adaptation px2rem sample code in vue
  • How to automatically convert px to rem in Vue project
  • Detailed explanation of Vue px to rem configuration

<<:  Learn SQL query execution order from scratch

>>:  Linux (center OS7) installs JDK, tomcat, mysql to build a java web project running environment

Recommend

Vue implements the shake function (compatible with ios13.3 and above)

Recently, I made a function similar to shake, usi...

Web front-end skills summary (personal practical experience)

1. Today, when I was making a page, I encountered ...

VMware installation of Centos8 system tutorial diagram (command line mode)

Table of contents 1. Software and system image 2....

Detailed tutorial on running Tomcat in debug mode in IDEA Maven project

1. Add the following dependencies in pom.xml <...

How to install WSL2 Ubuntu20.04 on Windows 10 and set up the docker environment

Enable WSL Make sure the system is Windows 10 200...

Detailed explanation of HTML form elements (Part 2)

HTML Input Attributes The value attribute The val...

Detailed explanation of how to use the calendar plugin implemented in Vue.js

The function to be implemented today is the follo...

Sliding menu implemented with CSS3

Result:Implementation code: <!DOCTYPE html>...

Detailed explanation of Vue's monitoring method case

Monitoring method in Vue watch Notice Name: You s...

A few things about favicon.ico (it’s best to put it in the root directory)

Open any web page: for example, http://www.baidu....