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

Detailed tutorial on installing Docker on CentOS 7.5

Introduction to Docker Docker is an open source c...

A brief analysis of the best way to deal with forgotten MySQL 8 passwords

Preface Readers who are familiar with MySQL may f...

MySQL multi-table query detailed explanation

Time always passes surprisingly fast without us n...

Some pitfalls of JavaScript deep copy

Preface When I went to an interview at a company ...

CentOS 7.9 installation and configuration process of zabbix5.0.14

Table of contents 1. Basic environment configurat...

How to use vue-bootstrap-datetimepicker date plugin in vue-cli 3

Demand Background Recently, I plan to use Vue and...

How to build a SOLO personal blog from scratch using Docker

Table of contents 1. Environmental Preparation 2....

MySQL query redundant indexes and unused index operations

MySQL 5.7 and above versions provide direct query...

Explain the difference between iframe and frame in HTML with examples

I don't know if you have used the frameset at...

Vue implements the full selection function

This article example shares the specific code of ...

js date and time formatting method example

js date time format Convert the date and time to ...

Install and configure ssh in CentOS7

1. Install openssh-server yum install -y openssl ...