Note: Before we start, please ask engineers working on mobile interfaces to add the following meta to the header:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
Copy the code

1. Percentage

.test{
    width: 20%
}
Copy the code
  • advantages

    • The code is simple
  • disadvantages

    • It’s inconvenient to calculate

Second, the media query

  • Implementation approach
@media screen and (min-width: 320px) and (max-width: 650px) { .class { float: left; }}
@media screen and (min-width: 650px) and (max-width: 980px) { .class { float: right; }}
@media screen and (min-width: 980px) and (max-width: 1240px) { .class { float: clear; }} @media screen and (device-width: 640px) { html { font-size: 12px; } } @media screen and (device-width: 750px) { html { font-size: 16px; } } @media screen and (device-width: 1240px) { html { font-size: 20px; }}Copy the code
  • advantages

    • You just need to write the CSS code
  • disadvantages

    • It is not flexible enough to calculate the exact value of each device, so only the range value can be taken

    • With so many screens and varying resolutions, it’s impossible to write CSS code for each model

    • Only a few mainstream devices can be chosen for perfect fit

    • Fault type switching changes

    • Large amount of code

Third, the vh/vw

  • The interpretation of the viewport

On the desktop, the viewport refers to the viewport area of the browser on the desktop; The mobile terminal is more complex, which involves three viewports: Layout Viewport, Visual Viewport and Ideal Viewport. The “viewport” in viewport unit, on the desktop side, undoubtedly refers to the viewport area of the browser; On mobile, it refers to the Layout Viewport of the three viewPorts.

  • Viewport units mainly include the following four:
  1. Vw: 1VW is equal to 1% of the viewport width
  2. Vh: 1vh equals 1% of the viewport height
  3. Vmin: Choose the smallest of vw and vH
  4. Vmax: Pick the largest of vw and vH
  • The difference between viewports and % units:

Viewport units are different from % units. Viewport units are defined according to the percentage of viewport size depending on the size of the viewport.

The % unit is the ancestor element that depends on the element.

Unit measurement, viewport width is 100VW, height is 100vh (left for portrait, right for landscape)

For example, if the browser viewport size is 650px on the desktop, 1VW = 650 * 1% = 6.5px (this is a theoretical calculation, if the browser does not support 0.5px, the actual rendering might be 7px).

Method 1: Use only VW as the CSS unit

  • Instead of using VW units as the only CSS units used, we followed the rule of converting the dimensions of the design to VW units
// The size of the iPhone 6 was used as a baseline for the design draft
$vm_base: 375; 
@function vw($px) {@return ($px / 375) * 100vw;
}
Copy the code
  • Use VW as the CSS unit for text, width, height, spacing, etc
.test {
    padding: vm(15) vm(10) vm(10);
    font-size: vm(10); 
}
Copy the code
  • The physical pixel lines (that is, 1px off the normal screen and 0.5px off the hd screen) are implemented using the Transform property Scale.
.test {
    position: relative;
    &::after {
        // Implement 1 physical pixel bottom border line
        content: ' ';
        position: absolute;
        z-index: 1;
        pointer-events: none;
        background-color: #ddd;
        height: 1px;
        left: 0;
        right: 0;
        top: 0;
        @media only screen and (-webkit-min-device-pixel-ratio: 2) {
            -webkit-transform: scaleY(0.5);
            -webkit-transform-origin: 50% 0%; }}... }Copy the code
  • For graphs that need to maintain their aspect ratio, use padding-top
.test {
    position: relative;
    padding-top: percentage(100/700); / / use the padding - top
    height: 0;  // This can't be saved
    overflow: hidden;
    img {
        width: 100%;
        height: auto;
        position: absolute;
        left: 0;
        top: 0; }}Copy the code

Question interrupt:

  • When margin-top and padding-top are percentages, how are they calculated respectively?

Whether margin-top/margin-bottom or margin-left/margin-right (like padding), percentage is calculated relative to the width of the nearest parent block-level element

  • Why is the percentage of margin-top/margin-bottom also relative to width and not height?

The definitive guide to CSS:

Most elements in a normal flow will be tall enough to contain their descendants (including margins). If an element’s upper and lower margins are a percentage of the height of the parent element, this can lead to an infinite loop in which the height of the parent element increases to accommodate the increase in margins of its descendants, and accordingly, The upper and lower margins increase as the parent element height increases, so the loop goes on forever.

  • Padding-top :(percentage) is commonly used to achieve a responsive background image.

Rationale for implementation: The technique of maintaining the aspect ratio of elements using percentages

For example, an image is 1024 pixels wide and 316 pixels high; Now the padding-top = (height/width) * 100% = (316/1024) * 100% = 30.85%;

<div class="wrap"> <div class="inner"></div> </div> .wrap{ max-width: 1024px; }. Inner {padding - top: 30.85%; /* 316 / 1024 */ background: url("http://images2015.cnblogs.com/blog/561794/201603/561794-20160310002800647-50077395.jpg") no-repeat; background-size:cover; background-position:center; //IE8 and below do not support background-size:cover, for compatibility with browsers below IE}Copy the code

Method a page looks fit very well, but you will find that since it is using the viewport the layout of the unit, depends on the size of the viewport automatic scaling, regardless of the viewport is too big or too small, it is also as the viewport is too big or too small, lost the limitation of maximum minimum width, so consider combining with rem.

Method 2: With VW and REM, the layout is more optimized

  1. You can dynamically change the size of the root element by giving it vw units that change with the viewport.
  2. Limit the maximum and minimum font size for the root element, along with the body plus the maximum and minimum widths
Rem conversion: 75px is just a convenience, 750px-75px, 640-64px, 1080px-108px, and so on
$vm_fontsize: 75; // iPhone 6 size of the root element size reference value
@function rem($px) {@return ($px / $vm_fontsize ) * 1rem;
}
// The root element size is in vw
$vm_design: 750;
html {
    font-size: ($vm_fontsize / ($vm_design / 2)) * 100vw; 
    // At the same time, use Media Queries to limit the maximum and minimum values of root elements@media screen and (max-width: 320px) { font-size: 64px; } @media screen and (min-width: 540px) { font-size: 108px; }}// Body also adds a Max/min width limit to avoid the default 100% width block element being too large or too small to follow body
body {
    max-width: 540px;
    min-width: 320px;
}
Copy the code

Compared with Method 1, I prefer Method 2 for the following two reasons: First, method 2 provides better visual experience for users and increases the limit of maximum and minimum width; Second, more importantly, if the mainstream REM flexible layout method is selected as the adaptation page method of project development, then method 2 is more suitable for the later project to transition from REM unit to VW unit. Just by changing the calculation of the root element size, you can seamlessly transition to another CSS unit without any other processing, and the use of VW units would certainly be a better fit, which is currently limited to compatibility support.

Method 3: Mix VW and VH

Use vw and VH as CSS units to set text, layout height, width, spacing,

  • advantages

    • Good experience, pure CSS
  • disadvantages

    • Poor compatibility (supported in mobile terminal iOS 8 or above and Android 4.4 or above, supported in wechat X5 kernel)

Four, rem

The REM attribute refers to setting the font size of an element relative to the root element. It can also be used to set the height of a series of units that can be marked with PX.

  • Implementation approach

Let’s say our UI design standard is the iphone5s, and the iphone5 series has a screen resolution of 640. For the sake of uniformity, we set the root element font size to 100px for iphone5 resolution;

html {
    font-size: 100px;
}
Copy the code

Based on this, a ratio value of 6.4 can be calculated. We can know the font size of the root element on devices with other mobile phone resolutions. We need to take into account that if it is a mobile device, the screen will have an upper and lower limit. The resolution can be controlled within a certain range, beyond which we will not increase the font size of the root element:

var deviceWidth = document.documentElement.clientWidth > 1300 ? 1300 : document.documentElement.clientWidth;
document.documentElement.style.fontSize = (deviceWidth / 6.4) + 'px'; So let's think about if I rotate the screenwindow.onresize = _.debounce(function() { var deviceWidth = document.documentElement.clientWidth > 1300 ? 1300 : document.documentElement.clientWidth; 
document.documentElement.style.fontSize = (deviceWidth / 6.4) + 'px'; },50);
Copy the code

In head, we add the above code to dynamically change the font size of the root node.

For 320-resolution devices, the 1px border will be compressed to 0.5px, and you can set different meta values for different devices

So the final code is zero

<meta name="viewport" content="width=device-width,user-scalable=no,maximum-scale=1" />
<script type="text/javascript">
    (function() {
        // deicePixelRatio: device pixel
        var scale = 1 / devicePixelRatio;
        // Set the meta compression interface to simulate the device's high resolution (taobao and netease News's mobile Web end adopts this method)
        document.querySelector('meta[name="viewport"]').setAttribute('content'.'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
        // Add a throttling function to improve performance
        var reSize = _.debounce(function() {
            var deviceWidth = document.documentElement.clientWidth > 1300 ? 1300 : document.documentElement.clientWidth;
            // Using a font size of 100px at 640 pixels, we get a font size of 6.4
            document.documentElement.style.fontSize = (deviceWidth / 6.4) + 'px';
        }, 50);

        window.onresize = reSize; }) ();</script>
<style type="text/css">
html {
    height: 100%;
    width: 100%;
    overflow: hidden;
    font-size: 16px;
}
Copy the code
  • advantages

    • No need to adjust styles on different screens (no extra CSS code)
  • disadvantages

    • Modifying script parameters in HTML can easily affect the whole world
    • You need an embedded script to dynamically calculate the root element size to keep CSS and JS coupled together

Flexible layout flexbox

The container has several important properties:

flex-direction
flex-wrap
flex-flow
justify-content
align-items
align-content
Copy the code

Project attributes:

order
flex-grow
flex-shrink
flex-basis
flex
align-self
Copy the code

Note:

The order attribute defines the order of items. The smaller the value is, the more advanced it is. The default value is 0.

The Flex-Grow property defines the project’s zoom scale, which defaults to 0, or no zoom if there is free space.

The Flex-shrink attribute defines the scale by which a project shrinks. The default is 1, that is, if there is insufficient space, the project shrinks.

The Flex-basis property defines the main size of the project before allocating extra space. Based on this property, the browser calculates whether the main axis has extra space. Its default value is Auto, the original size of the project.

The flex attribute is short for flex-grow, flex-shrink, and flex-basis. The default value is 0 1 Auto. The last two attributes are optional.

The align-self property allows a single item to have a different alignment than other items, overriding the align-items property. The default value is auto, which inherits the align-items property of the parent element. If there is no parent element, it equals stretch.

See the layout tutorial for details

  • Advantages:

    • The size and height of all elements in the interface are adjusted for different devices with different resolutions and screen widths, such as elements, fonts, images and heights. Simply put, the font you see and the height and width of elements are different on different screens.

Despite these adaptations, if the screen span is too large, you may need to not just change the style, but redesign the page layout. Select the corresponding mode according to the scene in the work.

conclusion

Here are a few key points:

Five kinds of adaptive methods:

  1. The percentage
  2. vm/vh
  3. flexbox
  4. media
  5. rem

Physical pixel line (1px under normal screen, 0.5px under HD screen) solution:

    1. This can be implemented using the Transform property scale
    1. You can set meta in REM mode
document.querySelector('meta[name="viewport"]').setAttribute('content'.'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
Copy the code

Whether margin-top/margin-bottom or margin-left/margin-right (like padding), percentage is calculated relative to the width of the nearest parent block-level element.

Padding-top :(percentage) is generally used to achieve a responsive background image.

When controlling at 1 screen, you can use a combination of VW and VH as CSS units

reference

caibaojian.com/vw-vh.html

www.jianshu.com/p/8f7f736fb…