Responsive layout

Responsive layout

When I write the project, I use the responsive layout to find the information, harvest and Bug
The following articles quoted by other authors. If there is infringement, please contact to delete it!

doubt

Why can't 1rem be 1px

The minimum font size set by the current browser is 12px, so the browser automatically recognizes HTML {font size: 1px} as HTML {font size: 12px}, so the effect is 1rem = 12px.

After adjusting the minimum font size of the browser, it is also verified that the above reasons are correct.

Therefore, it is set to 1rem=100px, which is also the simplest development method.

be careful

  1. Width requires percentage

    For example:

    #head { width: 100% }
    #content { width: 50%; }
    
  2. Method for processing picture scaling

    • A simple solution can use percentages, but this is not friendly and will enlarge or shrink the picture. Then you can try to specify the maximum width of the picture as a percentage. If the picture exceeds, zoom out. If the picture is small, output it in full size.
    img { width: auto; max-width: 100%; }
    
    • Use:: before and:: after pseudo elements + content attributes to dynamically display some content or do other cool things css3 In, any element can use the content attribute. This method combines the attr attribute of css3 with the HTML Functions of custom attributes: HTML Structure:
    <img src="image.jpg"
         data-src-600px="image-600px.jpg"
         data-src-800px="image-800px.jpg"
         alt="">
    

    CSS Control:

    @media (min-device-width:600px) {
        img[data-src-600px] {
            content: attr(data-src-600px, url);
        }
    }
    
    @media (min-device-width:800px) {
        img[data-src-800px] {
            content: attr(data-src-800px, url);
        }
    }
    
  3. Other properties

    For example, pre, iframe, video, etc. all need to control the width as well as img. For table, it is recommended not to add padding attribute, and use content centering in low resolution:

    table th, table td { padding: 0 0; text-align: center; }
    

programme

PC end

Method 1

   function setRem() {
        var ui_w = 375;
        // Gets the width of the screen
        var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
        console.log(ui_w, clientWidth);
       // Dynamically change the font size of html root node through js
        var html_ = document.getElementsByTagName('html')[0];
       html_.style.fontSize = (clientWidth / ui_w) * 10 + 'px';
   }
   // window.onresize browser resized execution event
   window.onresize = setRem;

Mobile terminal

Method 1

The mobile terminal adapts to rem alone. If the HTML font is set, the mobile phone font will be changed and the element size will be changed

Solution: you can introduce this js

'use strict'
!(function(e, t) {
  var n,
    i = document,
    d = window,
    o = i.documentElement,
    a = document.createElement('style')
  function s() {
    var n = o.getBoundingClientRect().width
    n > (t = t || 540) && (n = t)
    var i = (100 * n) / e
    a.innerHTML = 'html{font-size:' + i + 'px;}'
  }
  if (o.firstElementChild) o.firstElementChild.appendChild(a)
  else {
    var r = i.createElement('div')
    r.appendChild(a), i.write(r.innerHTML), (r = null)
  }
  s(),
    d.addEventListener(
      'resize',
      function() {
        clearTimeout(n), (n = setTimeout(s, 300))
      },
      !1
    ),
    d.addEventListener(
      'pageshow',
      function(e) {
        e.persisted && (clearTimeout(n), (n = setTimeout(s, 300)))
      },
      !1
    ),
    'complete' === i.readyState
      ? (i.body.style.cssText =
          'fontSize:16px;maxWidth:' + t + 'px;margin:0 auto;')
      : i.addEventListener(
          'DOMContentLoaded',
          function(e) {
            i.body.style.cssText =
              'font-size:16px;max-width:' + t + 'px;margin:0 auto;'
          },
          !1
        )
})(750, 750)

Then directly replace px/100 on your design drawing with rem

Method 2

 (function () {
    function setRootFontSize() {
        let dpr, rem, scale, rootWidth;
        let rootHtml = document.documentElement;
    
        dpr = window.devicePixelRatio || 1; //Mobile terminal must be set
        //Limit the minimum width of the presentation page
        rootWidth = rootHtml.clientWidth < 1366 ? 1366 : rootHtml.clientWidth;
        rem = rootWidth * dpr / 19.2; // 19.2 = dimension width of design drawing 1920 / 100 (REM of design drawing = 100)
        scale = 1 / dpr;
    
        // Set the viewport and zoom to achieve HD effect (added by mobile terminal)
        let vp = document.querySelector('meta[name="viewport"]');
        vp.setAttribute('content', 'width=' + dpr * rootHtml.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no');
    
        // Dynamic write style
        rootHtml.style.fontSize = `${rem}px`;
    }
    setRootFontSize();
    window.addEventListener("resize", setRootFontSize, false);
    window.addEventListener("orientationchange", setRootFontSize, false); //Mobile terminal
})();

Method 3

(function(){
var originWidthByDesign = 750 / 2;
var originRootFontSize = 50;
var maxLimitWidth = 667;
var doc = document.documentElement;
var div = document.createElement('div');
div.setAttribute('style', 'font-size: 1rem');
if (!!document.addEventListener && '1rem' === div.style.fontSize) {
var reCalculate = function reCalculate() {
var clientWidth = doc.clientWidth;
if (!clientWidth) {
return;
}
clientWidth = clientWidth < maxLimitWidth ? clientWidth : maxLimitWidth;
doc.style.fontSize = originRootFontSize * clientWidth / originWidthByDesign + 'px';
doc.style.display = 'none';
doc.clientWidth;
doc.style.display = '';
};
window.addEventListener('resize', reCalculate, false);
document.addEventListener('DOMContentLoaded', reCalculate, false);
reCalculate();
}
function getQueryString (name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
})()

Method 4

flexible.js mobile terminal adaptive scheme

mode

1. Media inquiry

Note: IE6, 7 and 8 do not support media query

Split point

  1. 600px,900px,1200px,1800px

  2. 480px,800px,1400px,1400px

  3. Mobile priority OR PC priority

    The following style overrides the previous style. Therefore, min width is preferred for mobile terminal and max width is preferred for PC terminal.

  4. Mobile priority

    /* iphone6 7 8 */
    body {
        background-color: yellow;
    }
    /* iphone 5 */
    @media screen and (max-width: 320px) {
        body {
          background-color: red;
        }
    }
    /* iphoneX */
    @media screen and (min-width: 375px) and (-webkit-device-pixel-ratio: 3) {
        body {
          background-color: #0FF000;
        }
    }
    /* iphone6 7 8 plus */
    @media screen and (min-width: 414px) {
        body {
          background-color: blue;
        }
    }
    /* ipad */
    @media screen and (min-width: 768px) {
        body {
          background-color: green;
        }
    }
    /* ipad pro */
    @media screen and (min-width: 1024px) {
        body {
          background-color: #FF00FF;
        }
    }
    /* pc */
    @media screen and (min-width: 1100px) {
        body {
          background-color: black;
        }
    }
    
  5. PC priority

    /* pc width > 1024px */
        body {
            background-color: yellow;
        }
    /* ipad pro */
    @media screen and (max-width: 1024px) {
        body {
            background-color: #FF00FF;
        }
    }
    /* ipad */
    @media screen and (max-width: 768px) {
        body {
            background-color: green;
        }
    }
    /* iphone6 7 8 plus */
    @media screen and (max-width: 414px) {
        body {
            background-color: blue;
        }
    }
    /* iphoneX */
    @media screen and (max-width: 375px) and (-webkit-device-pixel-ratio: 3) {
        body {
            background-color: #0FF000;
        }
    }
    /* iphone6 7 8 */
    @media screen and (max-width: 375px) and (-webkit-device-pixel-ratio: 2) {
        body {
            background-color: #0FF000;
        }
    }
    /* iphone5 */
    @media screen and (max-width: 320px) {
        body {
            background-color: #0FF000;
        }
    }
    

2. Percentage layout

The grid system in Bootstrap uses percentage to define the width and height of elements. CSS3 supports the maximum and minimum height. Percentage and max(min) can be used together to define the width and height of elements under different devices.

  1. Height or width is the height and width relative to the parent element, respectively

  2. The height of top and bottom relative to the parent element of non static positioning (default positioning)

  3. The width of left and right relative to the parent element of non static positioning (default positioning)

  4. padding and margin are relative to the width of the parent element

  5. Border radius is the width relative to itself

  6. translate and background size are relative to themselves

  7. border and font size cannot be set by percentage

Disadvantages:

  1. It is difficult to calculate and convert it into percentage units.
  2. Different references
/* pc width > 1100px */
html, body { margin: 0;padding: 0;width: 100%;height: 100%;}
aside {
    width: 10%;
    height: 100%;
    background-color: red;
    float: left;
}
main {
    height: 100%;
    background-color: blue;
    overflow: hidden;
}
/* ipad pro */
@media screen and (max-width: 1024px) {
    aside {
      width: 8%;
      background-color: yellow;
    }
}
/* ipad */
@media screen and (max-width: 768px) {
    aside {
      float: none;
      width: 100%;
      height: 10%;
      background-color: green;
    }
    main {
      height: calc(100vh - 10%);
      background-color: red;
    }
}
/* iphone6 7 8 plus */
@media screen and (max-width: 414px) {
    aside {
      float: none;
      width: 100%;
      height: 5%;
      background-color: yellow;
    }
    main {
      height: calc(100vh - 5%);
      background-color: red;
    }
}
/* iphoneX */
@media screen and (max-width: 375px) and (-webkit-device-pixel-ratio: 3) {
    aside {
      float: none;
      width: 100%;
      height: 10%;
      background-color: blue;
    }
    main {
      height: calc(100vh - 10%);
      background-color: red;
    }
}
/* iphone6 7 8 */
@media screen and (max-width: 375px) and (-webkit-device-pixel-ratio: 2) {
    aside {
      float: none;
      width: 100%;
      height: 3%;
      background-color: black;
    }
    main {
      height: calc(100vh - 3%);
      background-color: red;
    }
}
/* iphone5 */
@media screen and (max-width: 320px) {
    aside {
      float: none;
      width: 100%;
      height: 7%;
      background-color: green;
    }
    main {
      height: calc(100vh - 7%);
      background-color: red;
    }
}

3. rem layout

rem is based on the font size of the HTML root

em is based on the font size of the parent element

4. Viewport units

Companymeaning
vwRelative to the width of the window, 1vw is equal to 1% of the width of the viewport, that is, the width of the window is 100vw
vhRelative to the height of the window, 1vh is equal to 1% of the height of the viewport, that is, the height of the window is 100vh
vminThe smaller of vw and vh
vmaxThe larger of vw and vh
Companymeaning
%Most elements are relative to their ancestors, but also to themselves (for example, border radius, translate, etc.)
vw/vhRelative window size

5. Flexible layout

Most devices, especially mobile terminals, support FLEX well, so they can be used safely.

6. Picture response

The picture response here includes two aspects: one is size adaptation, which can ensure that the picture is compressed and stretched under different screen resolutions; One is to select high-resolution pictures as much as possible according to different screen resolutions and device pixel ratio, that is, when high-definition pictures or large pictures are not required on the small screen, so we can reduce the network bandwidth by replacing them with small pictures.

1. Use max width:

Image adaptation means that the image can be scaled according to the size of the container. The following code can be used:

img {
    display: inline-block;
    max-width: 100%;
    height: auto;
}

The inline block element is rendered inline relative to the content around it, but unlike inline, in this case, we can set the width and height. Max width ensures that the picture can be expanded with the container (i.e. ensure that all pictures are displayed at a maximum of 100% of their own. At this time, if the element containing the picture is smaller than the inherent width of the picture, the picture will be scaled to occupy the maximum available space), while height of auto ensures that the picture can be scaled in equal proportion without distortion. If it is a background picture, use the background size attribute flexibly.

So why not use width: 100%? Because this rule causes it to appear as wide as its container. When the container is much wider than the picture, the picture will be unnecessarily stretched.

2. Use srcset
<img srcset="photo_w350.jpg 1x, photo_w640.jpg 2x" src="photo_w350.jpg" alt="">

If the dpi of the screen is 1, the 1-fold graph will be loaded, and if dpi = 2, the 2-fold graph will be loaded. The dpi of the mobile phone and mac basically reaches more than 2. In this way, the traffic will not be wasted for the ordinary screen, and there is a high-definition experience for the retinal screen.

If the browser does not support srcset, the pictures in src will be loaded by default.

But you will find that this is not the case. In Chrome on Mac, it will load the 2x one in srcset at the same time, and then load the one in src and load two pictures. The sequence is to load all srcset first, and then load src. This strategy is strange. It actually loads two pictures. If you don't write src, you won't load two pictures, but the compatibility is not so good. This may be because the browser thinks that since there is srcset, there is no need to write src. If src is written, the user may be useful. If you use picture, you won't load two

3. Use background image
.banner{
  background-image: url(/static/large.jpg);
}
@media screen and (max-width: 767px){
  background-image: url(/static/small.jpg);
}
4. Use picture label

picturefill.min.js : solve the problem that IE and other browsers do not support

<picture>
    <source srcset="banner_w1000.jpg" media="(min-width: 801px)">
    <source srcset="banner_w800.jpg" media="(max-width: 800px)">
    <img src="banner_w800.jpg" alt="">
</picture>
<!-- picturefill.min.js solve IE Other browsers do not support <picture> Question of -->
<script type="text/javascript" src="js/vendor/picturefill.min.js"></script>

For example, IMG and img layout cannot be triggered. Img and img layout cannot be triggered at the top of the tag. Otherwise, IMG and img layout cannot be triggered.

In addition, using source, you can also do some compatible processing for the image format:

<picture>
    <source type="image/webp" srcset="banner.webp">
    <img src="banner.jpg" alt="">
</picture>

Summary: the implementation of responsive layout can be realized through media query + px, media query + percentage, media query + rem+js,vm/vh,vm/vh +rem. However, each method has its disadvantages. Media query needs to select the width of mainstream equipment as the breakpoint and write additional styles for adaptation, but it will be more troublesome. It can only present perfect adaptation under the selected dimensions of several mainstream equipment. In addition, the user experience is not friendly, and the layout remains unchanged under the resolution within the range of response breakpoints, At the moment of responding to the breakpoint switching, the layout brings fault switching changes, like a cassette player "clicking" again and again. Adapting by percentage is first of all troublesome to calculate. Second, if percentage is used in each attribute, the attribute of the relative element is not unique, which makes it easy for us to use percentage unit to complicate the layout problem. Through the elastic layout of dynamic calculation in rem unit, a script needs to be embedded in the head to monitor the change of resolution and dynamically change the font size of the root element, so as to couple CSS and JS. By using pure CSS viewport units to realize the page adaptation, it can not only solve the problem of response fault, but also solve the problem of script dependence, but the compatibility is not fully acceptable to the structure.

7. Set mate label

The View tab below tells the browser to use the width of the device as the view width and prohibits initial scaling. Add this meta tag to the < head > tag.

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

[1] (the user scalable = no attribute can solve the problem that the iPad can only return to the specific size after switching the horizontal screen.)

Forming scheme of responsive layout

Now css and UI framework have considered the problem of adapting to different screen resolutions. In actual projects, we can directly use these new features and frameworks to realize responsive layout. The following options are available:

  • Use the above methods to implement it yourself, such as CSS3, media query, REM, vw, etc
  • Flex flexible layout, poor compatibility
  • Grid layout, poor compatibility
  • Columns grid system often needs to rely on a UI library, such as Bootstrap

Key points of responsive layout

In the actual project, we may need to integrate the above schemes, such as using rem for font adaptation, srcset for image response, rem, flex and grid system for width, and then we may also need to use media query as the basis for responsive layout. Therefore, integrate the above implementation schemes, The following points should be paid attention to when implementing responsive layout in the project:

  • Set viewport
  • Media query
  • Font adaptation (font unit)
  • Percentage layout
  • Picture adaptation (picture response)
  • Combined with the formed schemes such as flex, grid, BFC, grid system, etc

BUG encountered

1. Font Boosting of WebKit

The default minimum is 12px

In principle, the pseudo code of the calculation rule of Font Boosting is as follows:

multiplier = Math.max(1, deviceScaleAdjustment * textScalingSlider * systemFontScale * clusterWidth / screenWidth);
if (originFontSize < 16) {
    computedFontSize = originFontSize * multiplier;
}
else if (16 <= originFontSize <= (32 * multiplier - 16)) {
    computedFontSize = (originFontSize / 2) + (16 * multiplier - 8);
}
else if (originFontSize > (32 * multiplier - 16)) {
    computedFontSize = originFontSize;
}
    originFontSize: Original font size
    computedFontSize: Calculated font size
    multiplier: The conversion factor is calculated from the following values:
        deviceScaleAdjustment: When specified viewport width=device-width This value is 1 when, otherwise it is 1.05 - 1.3 Between, there are special calculation rules
        textScalingSlider: The scale manually specified in the browser. The default is 1
        systemFontScale: System font size, Android The device can be in「equipment - display - font size」The default value is 1
        clusterWidth: application Font Boosting How to determine the width of this element (refer to the upper two fonts of this element)
        screenWidth: Device screen resolution( DIPs, Density-Independent Pixels),as iPhone 5 320

resolvent:

1.
body,body *{*
max-height:1000000px
}
or
p { max-height: 999999px; }  //It only works on Android
 or
max-height: 100%

2.use viewport of width Manually specify the width, but it has no effect on my page

3.to body set up max-width Equal to 99999 px(This is the only valid attribute, max-height Is invalid)

4.Label the part that caused the trouble separately max-width,So the problem won't arise

5.<meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, user-scalable=no"> The zoom ratio is set to 1, as for 1 px Such problems can be solved by other solutions.

6.set up text-size-adjust: none,However, most browsers are incompatible.

2. Browser compatibility problem - plug-in Autoprefixe

vscode search Autoprefixer

The configuration is as follows:

 "git.ignoreLimitWarning": true,

  "autoprefixer.browsers": [
    "> 1%", 
    "last 2 versions",
    "not ie <= 8",
    "ios >= 8", 
    "android >= 4.0",
    "firefox >= 8",
    "chrome >= 24",
    "Opera>=10"
    ],

Use the shortcut Ctrl+Shift+p to display all commands, then search for Autoprefixer, and then click it

Knowledge:

  • -moz stands for firefox browser private properties
  • -ms represents the private property of IE browser
  • -webkit represents the private properties of chrome and safari
  • -o represents opera private attribute

3. The style of extreme speed mode of Baidu, quark browser on mobile terminal and 360 browser on PC terminal is chaotic

4. vue after packaging, the width of element component will change

5. Lead in components

<script>
import Car from './components/Car.vue'
  export default {undefined
  name: 'App',
  components:{//Add custom component
   Car
  }
 }
 </script>

6. Import global components

main.js:

//Loading components
import loadingLayer from "@/components/loadingLayer.vue"
Vue.component("loadingLayer",loadingLayer)

7. Value transfer between sibling components

**Step 1: create a js file, eventbus js, * * anywhere. I put it in the src directory

import Vue from 'vue'
export default new Vue()

Step 2: in the top component, introduce js just now

import '@/eventBus.js' 

Then define a function (the component to send data) in methods

methods:{
    changesize(){
        eventBus.$emit('add',this.arg)
    }
}

Suppose you click button to trigger the changesize function, and then pass arg out

Step 3: in the left component, let us also introduce eventbus JS, and then use the created lifecycle function (the component to receive the data)

created(){
    eventBus.$on('add',(message)=>{
        //The value of some operations is the message passed from the component
        console.log(message)
    })
},

8. Define global variables

Read only global variable

Scheme 1: Vue prototype
Vue.prototype.baseURL = "http://120.76.52.65/phpsaomaserver";
Scheme 2: set and import global variable files

Create a store Vue file and expose it to save global variables

<script>
const name = 'shenxianhui';
const age = 24;
 
export default {
    name,
    age
};
</script>

In test Used in Vue components

<template>
    <div>{{ myName }}</div>
    <div>{{ myAge }}</div>
</template>
 
<script>
import myStore from '@/components/Store'; // Reference module
 
export default {
    data () {
        return {
            myName: myStore.name,
            myAge: myStore.age
        }
    }
}
</script>

Readable and writable global variables

  1. main. Defined in JS
    new Vue({
        router,
        data: function(){
            return {
                ORDERID: 'PLDxxxxxx0001',
            }
        },
        render: h => h(App)
    }).$mount('#app');
    
  2. quote
    // modify
    this.$root.ORDERID = "xxxxx"
    // quote
    let orderId = this.$root.ORDERID 
    

Local storage

HTML5 NEW

localStorage: permanent and always exists in the browser, unless the user manually clears localStorage; Generally, 5M browsers are slightly different; Do not participate in communication with the server.

sessionStorage: valid under the current session, and invalid after closing the page and clearing the browser; Generally, 5M browsers are slightly different; Do not participate in communication with the server.

API: the API forms of the two are the same

localStorage.setItem("key","value");  //Store a value "value" with the name "key"

localStorage.getItem("key");  //Gets the value with the name "key"

localStorage.removeItem("key");  //Delete the information named "key".

localStorage.clear();  //Clear all information in localStorage
Set instance of localStorage expiration time
let setTime = new Date().getTime() + (1000 * 60);    // Test, set the data to expire after 1 minute

localStorage.setItem('test', JSON.stringify({
    data: 'data1',
    expiration: setTime
}));

let data = localStorage.test;
data = JSON.parse(data)

let time = data.expiration;
let value = data.data;

if(new Date().getTime() > time) {
    delete localStorage.test;
    // Here we begin to execute the code that times out
}
else {
    // Here you start executing code that did not time out
}

Cookie storage

This method is not recommended. After all, due to the size limit, you also need to set the expiration time.

The cookie remains valid until the expiration time, even if the window or browser is closed;

The storage data size is about 4k;

There is a limit on the number (depending on browsing), which generally cannot exceed 20;

With the concept of domain, cookie s cannot be used with each other in different domains.

When communicating with the server, the subdomain name accesses http requests with a cookie under the primary domain name, which will slow down the access speed. If you use cookies to save too much data, it will cause performance problems.

9. Automatically synchronize to the server

Scheme 1: package of vue JSON file

"push": "npm run build && scp -r dist/* root@120.76.52.65:/www/wwwroot/120.76.52.65"

Password free login

  1. Log in to the pagoda to get the ssh key

  2. Import the key to the local ssh folder

  3. Configuration config file

    # Tencent lightweight cloud
    Host <host name>
    HostName <custom>
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/<Key file name>
    

Scheme 2: SFTP plug-in

configuration file

{
    "name": "Local folder name (customizable)",
    "host": "ip Or domain name",
    "protocol": "agreement:[sftp/ftp]default ftp",
    "port": 22,
    "username": "username",
    "password":"password",
    "remotePath": "Remote folder address, default/",
    "context": "Local folder address, default to vscode Workspace root",
    "uploadOnSave": true,
    "downloadOnOpen":false,
    "connectTimeout":300,
    "ignore": [
        "**/.vscode/**",
        "**/.git/**",
        "**/.DS_Store"
    ],
    "watcher": {
        "files": "*",
        "autoUpload": false,
        "autoDelete": false
    }
}
uploadOnSave: Local update file saves are automatically synchronized to remote files (renaming and deleting files are not synchronized)
downloadOnOpen: Download an open file from a remote server
ignore: Ignored files (matching files will not be synchronized)
watcher: Listener (you can rename and delete files)
autoUpload: File changes are automatically synchronized (modified and renamed)
autoDelete: File deletion is automatically synchronized

example

{
    "name": "test", 
    "host": "abc.com",
    "protocol": "ftp",
    "port": 21,
    "username": "username",
    "password":"password",
    "remotePath": "/",
    "uploadOnSave": true,
    "connectTimeout":300,
    "ignore": [
        "**/.vscode/**",
        "**/.git/**",
        "**/.DS_Store"
    ],
    "watcher": {
        "files": "*",
        "autoUpload": false,
        "autoDelete": false
    }
}

10. Get node method

1. vue
 obtain dom Node can be used ref attribute
this.$refs.<ref Value of>

2. Primordial js
document.getElementById('<id>')
//The array obtained below needs to be added with [0] during operation
document.getElementsByName('<name The value of the property>')
document.getElementsByTagName('<Tag name>')
document.getElementsByClassName('<Class name>')

11. Several ways to modify ElementUI style

​ 1. New global style sheet

newly build global . css file, and in main JS. global.css files are generally placed in the style folder under SRC - > assets static resource folder, in main JS is quoted as follows:

import "./assets/style/global.css";

At global The style written in CSS file will override the default style of ElementUI in any vue single page.

​ 2. Add a new style tag to the current vue single page

After the style tag of the current vue single page, add a new pair of style tags. Do not add scoped attribute to the new style tag. The style written in the style tag with written scoped will not override the default style of ElementUI.

​ 3. Use / deep / depth to modify the label style or > > >

Find the class name of the ElementUI tag that needs to be modified, and then add / deep / before the class name to force the modification of the default style. This method can be directly used in the style tag with scoped attribute.

// Modify the default width of the cascading selection box
/deep/ .el-cascader {
  width: 100%;
}
<style scoped>
  .a >>> .b { /* ... */ }
//Cannot be used in less
</style>

//Defined as variable usage
//You can also alias > > > in the global style sheet, so you can directly use its alias such as @ {data} in any style tag of the page to modify the page style
//Multiple @{data} can be used at the same level, but cannot be nested with each other, otherwise it will not take effect
<style scoped lang='less'>
    @deep: ~'>>>';
      .box {
        @{deep} .title {
            ...
        }
      }
</style>

​ 4. Override the default style by inline style or bound class style

By using inline style and binding class style, you can directly override the default style in some labels, which is not very common. Specific examples are as follows:
How to inline style:

<el-button :style="selfstyle">Default button</el-button>
<script>
    export default {
      data() {
        return {
            selfstyle: {
                color: "white",
				marginTop: "10px",
				width: "100px",
				backgroundColor: "cadetblue"
            }
        };
      }
    }
</script>

Modify by binding style:

<el-button :class="[selfbutton]">Default button</el-button>
<script>
  export default {
    data() {
      return {
        selfbutton: "self-button"
      };
    } 
  }
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
.self-button {
    color: white;
    margin-top: 10px;
    width: 100px;
    background-Color: cadetblue;
}
</style>

​ 5. summary

The first way is to import css files globally, which is suitable for the overall modification of elementUI, such as the modification of overall color matching; The second way is to add a style tag, which can also achieve the effect of modifying the default style, but in fact, because the global style is modified, there may be conflicts when modifying the same style in different vue components.

The third way is to modify the default style in vue components conveniently through / deep /, and there will be no conflict with other pages.

The fourth method has great limitations and can be used, but it is not recommended.

Keywords: css3 Vue html

Added by hansman on Sat, 12 Feb 2022 00:01:52 +0200