Write in the previous,3 years of front-end development experience, at the beginning of the adaptation of the concept is only know REM, for a variety of forming layout or adaptation ideas, are very vague, there is no concept of the system, so do some homework, but also refer to many excellent blog ~ welcome to add ~

☞ Mobile end adaptation and PC end adaptation experience (2) (may be more complete

1. Related concepts

1 pixel

1. The pixel

A pixel is the smallest unit that makes up an image, the smallest unit on a display screen, and an image is made up of pixels, the more pixels there are per unit area, the better the result the pixel size is not absolute, it is determined by the resolution of the device

2. The resolution

Screen resolution: The number of pixels in the landscape and portrait of the screen, in px

The lower the resolution of a screen of the same size, the larger the unit pixel size, and the higher the resolution, the smaller the unit pixel size

Image resolution: refers to the number of pixels in an image, indicating the number of pixels in an image, both vertically and horizontally

The higher the resolution, the clearer the picture is of the same size.

3.PPI

Number of pixels per inch

PPI can be used to describe the sharpness of a screen as well as the quality of an image. The higher THE PPI, the clearer the screen.

4. Physical pixel of the device (physical resolution)

The actual resolution of the device is the number of pixels on the screen

Take iphone6 for example, the physical resolution is 750*1334, which is the number of led lights inside the display

5. Device-independent pixel DIPS (logical resolution)

A unit that tells phones of different resolutions what the size of the element they display on the interface is: how many pixels of the device are used as a pixel

Take iphone6 as an example, dips is 375* 667, which means 2*2 physical pixels as an independent pixel of the device

All kinds of devices, mobile phones, tablets, laptops and other logical pixels

Mobile phone: logical pixels between 3xx-4xx (short side)

Tablet: 10 inch tablet 7XX-8XX (short side)

Notebook: 13 “1280 (long side)

24 “display: 1920 (long side)

6. The device pixel ratio is DPR

The ratio of physical pixels to device independent pixels

A pixel in the CSS is an abstract unit. In different devices or environments,1px in the CSS represents different physical pixels of the device. 1px is not absolute, it only represents the smallest unit of the current device pixel.

On the PC side, 1px is equal to the physical pixel of a device, but the screen pixel density of mobile devices is getting higher and higher. On iphone6, one CSS pixel is equal to two physical pixels. Through DPR, we can know how many physical pixels a CSS pixel on the device represents

Get DPR: js:

window.devicePixelRatio
Copy the code

css:

-webkit-min-device-pixel-ratio
React Native: PixelRatio.get()
Copy the code

Why does the iphone6 have 375 logical pixels and 750 wide designs

The design scales as a 2x image, because the image is twice the size of the page, but the retina screen shrinks the image twice, making it more detailed and clear.

7. The CSS pixels

CSS pixels, one CSS pixel equals one device-independent pixel when the page scaling is 100%.

But CSS pixels are easily changed, and when the user zoomed in on the browser, the CSS pixels were enlarged, and one CSS pixel spanned more physical pixels.

Page scaling factor = CSS pixels/device-independent pixels.

2 viewport

1. Layout viewportslayout viewport

Layout viewport: the viewable area of the current browser, excluding the menu bar and the browser UI excluding the scroll bar

On the PC side, setting viewPort does not take effect and the layout viewport is always equal to the width of the browser window.

On mobile, scroll bars appear because the layout is 980px by default to make a website designed for a PC browser fully visible on a small screen on mobile

If you don’t specify an initial scale on the iPhone or iPad, the iPhone and iPad automatically calculate initial-scale to ensure that the width of the current Layout ViewPort is the width of the browser’s viewport when scaled

// Get the layout viewport width
document.documentElement.clientWidth / Height
Copy the code

2. Visual portsvisual viewport

Visual viewport: the area that the user currently sees, including the scroll bar. Default is equal to the current browser window size

The user zoomed in and out of the site, and the CSS pixel became larger. One CSS pixel could span more device pixels, and the area of the site that we could see would shrink, making the viewport smaller

Suppose you need 200 CSS pixels to fill the screen, but now you only need 100 CSS pixels to fill the screen, so the width of the visual port becomes 100px.

Similarly, when the user zooms in on the site, the area we see on the site becomes larger, and the visual port becomes larger

// Get the visual window width
window.innerWidth
Copy the code

3. Ideal viewportideal viewport

An ideal size for the layout viewport, only if the size of the layout viewport is equal to the size of the device screen.

The idea of the Ideal ViewPort is that sites designed for the Ideal ViewPort can be presented to the user at any screen resolution without manual scaling or horizontal scrollbars.

A 14px text, for example, won’t be too small to read on a high-density screen. Ideally, this 14px text will appear the same size on any density screen and at any resolution.

// Get the desired viewport width
window.screen.width
Copy the code

4. How do mobile terminals get the ideal viewport

<meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1; minimum-scale=1; user-scalable=no;" >Copy the code

The purpose of this meta tag is to make the width of the viewport in the current layout equal to the width of the device without allowing the user to manually zoom in and out

At this point, one CSS pixel is equal to one device-independent pixel, and the layout is based on the ideal viewport, so the page layout is roughly the same across devices.

To set the current viewport width to the ideal viewport width, you can set width=device-width or initial-scale=1. The ideal ViewPort width of the vertical screen prevails. Initial-scale =1; width=device-width =1;

Page zoom factor = ideal viewport width/layout viewport width

If the meta sets both initial-scale and width, the layout viewport takes the maximum value between the two

Reference: viewport parsing

5. Size of common get Windows

  • window.innerHeight: Gets the height of the browser’s visual viewport (including the vertical scroll bar).
  • window.outerHeight: Gets the height outside the browser window. Represents the height of the entire browser window, including the sidebar, window borders, and resize borders.
  • window.screen.Height: Get the screen to get the ideal viewport height, the value is fixed,Device resolution/Device pixel ratio
  • window.screen.availHeight: Height of the browser window available.
  • document.documentElement.clientHeight: Gets the height of the browser layout viewport, including inner margins, but excluding vertical scroll bars, borders, and margins.
  • document.documentElement.offsetHeight: includes inside margins, scroll bars, borders, and margins.
  • document.documentElement.scrollHeight: The minimum width required to fit all content in the viewport without using scroll bars. Measurement method andclientHeightSame: It contains the inner margin of the element, but does not include borders, margins, or vertical scrollbars.

The difference between responsive design and adaptive design: Responsive development of a set of interface, through detection of viewport resolution, for different clients in the client to do code processing, to show different layout and content; Adaptive needs to develop multiple sets of interfaces, through the detection of viewport resolution, to determine the current access device is PC, tablet, mobile phone, so as to request the service layer, return to different pages.

2. Common layout schemes

Fixed layout: use pixels as the basic unit of the page, and design only one set of sizes regardless of device screen and browser width; Swappable fixed layout: Also using pixels as page units, design several layouts with different widths based on mainstream device sizes. Select the most appropriate set of widths by identifying screen sizes or browser widths;

Flexible layout: Using percentage as the basic unit of the page, it can accommodate all device screen sizes and browser widths within a certain range, and make the best use of effective space to display the best results; Hybrid layout: Similar to flexible layout, it can accommodate all device screen sizes and browser widths within a certain range, and makes perfect use of effective space for best results; Just mix pixels and percentages as page units. Layout response: The responsive design of the page requires different widths of the same content. There are two ways: PC first (design from the PC side down); Mobile first (design from mobile up); Regardless of the design pattern, to accommodate all devices, the layout response inevitably requires some change in the layout of the module (the point at which the layout change occurs is called a breakpoint)

PC layout

1. Media query

Mainstream system resolution size

Then we’ll take a look at what the current mainstream systems and resolutions are

PC & MAC & Chrome

1280 x 800 1366 x 1024 (IPad Pro) 1440 x 900 1680 x 1050 1600 x 900 1920 x 1200 2560 x 1440 Higher 2880 x 1620 3200 x is ignored 1800 5120 x 2880Copy the code

PC & Windows & Chrome (or PC & MAC & Chrome & Peripheral Monitor)

1280 x 720/1024
1366 x 768
1440 × 900
1600 x 900
1920 x 1080
Copy the code

Mobile & Android

360 x 480
412 x 732
...
Copy the code

Mobile & IOS

IPhone 6:         375 x 667
IPhone 6 Plus:    414 x 736
IPhone X:         375 x 812
Copy the code

No IPad:

768 x 1024
Copy the code
General style
Note: The default style is written first/* Print style */
        @media print {}
    /* Small screen handheld devices such as mobile phones */
        @media screen and (min-width: 320px) and (max-width: 480px) {}
    /* Devices with width below 1024, such as tablets */
        @media only screen and (min-width: 321px) and (max-width: 1024px) {}
    /* PC client or large screen device: 1028px to larger */
        @media only screen and (min-width: 1029px) {}
    / * * / vertical screen
        @media screen and (orientation:portrait) {portrait}Landscape * / / *
        @media screen and (orientation:landscape){corresponding style}Copy the code
Mobile first:
/* 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; }} Copy the codeCopy the code
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; }}Copy the code
Media query plus REM layout
html{
   font-size:19.20 px.;  /* By default, the design is based on the design, divided by 100*/
   //1rem = 19.20 px.
}
@media only screen and (max-width: 1366px{/ /1rem = 13.66 px.;
   html{
      font-size:13.66 px.; }}#test{
   width:14.21875 rem;
}
Copy the code

Advantages: flexible in the face of different resolution devices, can quickly solve the problem of multi-device display adaptation

Disadvantages:

  • Only a perfect fit for the selected mainstream device sizes,
  • The user experience is also unfriendly, with the layout remaining unchanged at resolution within the range of the response breakpoint, and the layout introducing a fault-like switching change at the moment the response breakpoint switches
  • Code is cumbersome, heavy workload, low efficiency and long loading time
  • Changed the original site structure to a certain extent

2. Percentage layout

With percentage units, you can make the width and height of the components in the browser change with the height of the browser to achieve a responsive effect. The overall layout remains the same. The raster system in Bootstrap uses percentages to define the width and height of elements. CSS3 supports maximum and minimum heights.

Design method: use % % to define the width, the height is mostly fixed with PX, can be adjusted according to the viewport and the real-time size of the parent element, to accommodate as many resolutions as possible. Usually with max-width/min-width and other attributes to control the size flow range to avoid too large or too small impact on reading.

Specific analysis of percentages

  • The percentage of child elements height and width/ top and bottom, left, and right is relative to parent elements width, height
  • The padding/margin of the child element is relative to the width of the parent element, regardless of its height, either vertically or horizontally.
Percentage unit layout application

Set the padding-top to a percentage to implement an adaptive block of equal proportions

Adaptive rectangles:

<div class="trangle"></div>
Copy the code

Set styles to be adaptive:

// The rectangle will always be4:3
.trangle{
  height:0;
  width:100%;
  padding-top:75%; // Relative to the width75%
}
Copy the code

The sample

/* 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; }}Copy the code

Disadvantages:

  • Adaptive computing trouble
  • When percentages are used in individual attributes, the attributes of the relative elements are not unique, complicating the layout problem.
  • If the screen scale is too wide, it will not display properly on a screen that is too small or too large for its original design. Because the width is defined by % percentage, but the height and text size are mostly fixed by PX, so the display effect will become some page elements width is pulled very long under the mobile phone with large screen, but the height and text size are still the same as before, the display is very inconsistent.

3. Rem layout

REM is a new unit in CSS3, and it is highly supported on mobile, android2.x +,ios5+. The rem unit is determined by the font size of the root element. The font size of the root element provides a baseline. When the page size changes, you only need to change the value of font size, and then the size of the element with rem as the fixed unit will also change. Therefore, if rem is used to achieve a responsive layout, you only need to dynamically change the font size according to the size of the view container (em is relative to the parent element).

Rem responsive layout idea:

  • It is generally not desirable to set specific widths for elements, but you can set specific widths for small ICONS
  • The height value can be set to a fixed value, how big the design is, we are strict with how big
  • All set fixed values are usedremDo units (first set a reference value in HTML:pxandremThe corresponding proportion, and then obtain in the effect drawingpxThe value of the layout is converted toremValue)
  • Js takes the width of the real screen, divides it by the width of the design draft, calculates the proportion, resets the previous reference value according to the proportion, so that the project can be adaptive on the mobile end

Example 1:

Full screen 16:9 solution

  1. When CSS represents length, divide the length of the design by 192 to calculate the rem value.
  2. Page to write a section of JS code, according to our above formula to calculate and setFont size for HTML elementsValue.
export function init(screenRatioByDesign: number = 16 / 9) {
  let docEle = document.documentElement
  function setHtmlFontSize() {
    var screenRatio = docEle.clientWidth / docEle.clientHeight;
    var fontSize = (
      screenRatio > screenRatioByDesign
        ? (screenRatioByDesign / screenRatio)
        : 1
    ) * docEle.clientWidth / 10;

    docEle.style.fontSize = fontSize.toFixed(3) + "px";
  }
  setHtmlFontSize()
  window.addEventListener('resize', setHtmlFontSize)
}
Copy the code

3.[Webpack version] (github.com/QuellingBla…)

4. Original address

Example 2:

function refreshRem() {
    var docEl = doc.documentElement;
    var width = docEl.getBoundingClientRect().width;
    var rem = width / 10;
    docEl.style.fontSize = rem + 'px';
    flexible.rem = win.rem = rem;
}
win.addEventListener('resize', refreshRem);
Copy the code

Disadvantages of the REM layout:

In a responsive layout, the font size of the root element must be dynamically controlled through JS, which means that the CSS style and JS code have some coupling, and the code that changes font size must be placed before the CSS style

The REM layout is also by far the best way to fit multiple screens. By default our HTML tag font size is 16px, we use media query to set the font size for different devices.

4. Viewport unit: VW

Vh and VW schemes divide the visual viewport width window.innerWidth and visual viewport height window.innerHeight into 100 portions

Vw is also a relative unit to the layout viewport; 1vw is 1% of the layout viewport width. The familiar standard iPhone6 design is 750px wide. So 1vw = 1% viewport width, 100vw = 750px according to the design, 1vw = 7.5px.

The difference between VW and % is:

unit meaning
% Most are relative to ancestor elements, but also relative to themselves (border-radius, translate, etc.)

Body or HTML set to width:100% does not include the width of the page scroll bar
vw/vh Size relative to the window, not affected by the parent element

100vw includes the width of the page scroll bar, and 100vw is more than 100% wider with a vertical scroll bar

Vw units are similar to percentages, but there is a difference. Earlier we talked about the difficulty of converting percentage units. Here vw is more like “ideal percentage units”. For any level element, 1vw is equal to 1/100th of the view width in vw units.

Disadvantages:

  • pxConverted tovwIt may not be completely divisible, so there is a certain pixel difference.
  • For example, as a containervw.marginusingpxIt is easy to cause the overall width to exceed100vw, thus affecting the layout effect. Of course, we can also avoid, such as usingpaddingInstead ofmarginAnd cooperate withbox-sizingIn combination withcalc()Function use and so on

Advantages:

  • The VW layout is much purer and the code logic much clearer

There are two ways to implement responsiveness using viewport units:

1. Use vw as the CSS unit only
  • For converting the dimensions of the design to units, we compile using the Sass function

    //iPhone 6$VM_base:375; 
    @function vw($px) {
        @return ($px / 375) * 100vw; } Duplicate codeCopy the code
  • Use VW for text, layout width, spacing, and so on

    .mod_nav {
        background-color: #fff;
        &_list {
            display: flex;
            padding: vm(15) vm(10) vm(10); // internal spacing &_item {flex: 1;
                text-align: center;
                font-size: vm(10); // font size &_logo {display: block;
                    margin: 0 auto;
                    width: vm(40); / / widthheight: vm(40); / / heightimg {
                        display: block;
                        margin: 0 auto;
                        max-width: 100%;
                    }
                }
                &_name {
                    margin-top: vm(2); }}}} Copy codeCopy the code
  • The 1px physical pixel line (that is, 1px under normal screen and 0.5px under hd screen) is implemented using the Transform property Scale

    .mod_grid {
        position: relative;
        &::after{/ / implementation1The bottom border line of the physical pixelcontent: ' ';
            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%; }}... } Duplicate codeCopy the code
  • For graphs where you want to maintain the aspect ratio, you should use padding-top

    .mod_banner {
        position: relative;
        padding-top: percentage(100/700); / / usepadding-top
        height: 0;
        overflow: hidden;
        img {
            width: 100%;
            height: auto;
            position: absolute;
            left: 0;
            top: 0; }} Copy the codeCopy the code

5. Pair with a VW and REM

Although the page adapted by VW has a good effect, it uses viewport unit to realize the layout, and automatically scales depending on viewport size. Regardless of whether the viewport is too large or too small, it also loses the limitation of maximum and minimum width as it becomes too large or too small. At this time, we can combine REM to realize the layout

  • You can dynamically change the size of the root element by giving it vw units that change with the viewport

  • Limit the maximum and minimum font size for the root element, along with the body plus the maximum and minimum widths

    $vm_fontsize: 75; $vm_fontsize: 75; $vm_fontsize: 75; @function rem($px) {@return ($px / $vm_fontsize) * 1rem; } // The root element size uses vw unit $vm_design: 750; html { font-size: ($vm_fontsize / ($vm_design / 2)) * 100vw; @media Queries and (max-width: 320px) {font-size: 64px; } @media screen and (min-width: 540px) { font-size: 108px; {max-width: 540px;} // Add a Max/min width limit to the body element. min-width: 320px; } Duplicate codeCopy the code

6. Picture response

Here the picture response includes two aspects, one is the size of self-adaptation, so as to ensure that the picture in different screen resolutions appear compression, stretching; One is to choose images with as high resolution as possible depending on the screen resolution and pixel ratio of the device. That is, when high-definition images or large images are not needed on a small screen, we can use small images instead to reduce network bandwidth.

1. Use max-width (image adaptive) :

Image adaptation means that the image can be scaled to match the size of the container, using the following code:

img { display: inline-block; max-width: 100%; height: auto; } Duplicate codeCopy the code

An 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 image can be expanded equally as the container grows (i.e., all images can be displayed at a maximum of 100% of themselves). At this point, if the element containing the image is smaller than the inherent width of the image, the image will be scaled to fill the maximum available space), and the height of auto ensures that the image will be scaled equally without distortion. Be flexible with background-size for background images.

So why not use width: 100%? Because this rule causes it to appear as wide as its container. In cases where the container is much wider than the image, the image is stretched unnecessarily.

2. Use srcset
<img srcset=" photo_w350/jpg 1x, photo_w640.jpg 2x" SRC =" photo_w350/jpg "Alt =""> Copy the codeCopy the code

If the dPI of the screen is 1, the 1x image will be loaded, while the DPI of the screen is 2, the 2x image will be loaded. Basically, the DPI of mobile phones and Macs is above 2, which will not waste traffic for the ordinary screen, and the HD experience for the retina screen.

If the browser does not support srcset, images in SRC are loaded by default.

But you’ll notice that this is not the case. Chrome on the Mac will load the 2x image in srcset and the SRC image in srcset at the same time. Load all srcsets before loading SRC. This strategy is odd in that it loads two images, not two if you don’t write SRC, but it’s not as compatible. This is probably because the browser thinks that since it has srcset there is no need to write SRC, and if it does write SRC, the user might be useful. Using picture will not load two

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

Pictureflex.min. js: Solves the problem that Internet Explorer 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> <! <picture> <script type="text/javascript" SRC = "js/vendor/picturefill. Min. Js" > < / script > duplicate codeCopy the code

For example, the onload event is triggered in the IMG tag. Picture and Source are not layout. Their width and height are 0.

In addition, using Source, you can also do some compatibility processing for the image format:

<picture> <source type="image/webp" srcset="banner. Webp "> <img SRC ="bannerCopy the code

7. Special circumstances

Zoom properties
document.body.style.zoom = window.screen.width / 1920;
Copy the code
ScaleEle single screen application plug-in

8.PC adaptation of the molding scheme

Rem is used for font adaptation, SRCset is used for image responsiveness, and rem, Flex, raster system and so on can be used for width responsiveness, and then media query may be used as the basis of responsive layout. Therefore, based on the above implementation scheme, the following points should be paid attention to in the project to realize responsive layout:

  • Set the viewport
  • Media queries
  • Font fit (font unit)
  • Percentage layout
  • Picture adaptation (picture responsiveness)
  • Combined with Flex, grid, BFC, grid system and other formed solutions
  • A mix of streaming layout (that is, percentage layout) and media queries

Mobile terminal adaptation scheme

The general principles of mobile development are: text flow, control elasticity, image scaling.

1. Media query

  • Media queries can be adjusted for specific modules within specific screen widths in combination with percentages or Flex layouts.

  • The other is to combine REM and set different REM reference font sizes for devices with different screen widths.

The principle of same

2. The viewport

Direct proportional scaling

<script>
    const scale = window.screen.width / 750
    document.write(`<meta name="viewport" content="initial-scale=${scale}"> `)
</script>
Copy the code

Cons: too rough, viewPort is set up to affect the whole world, where it doesn’t need to be scaled, and may affect third-party libraries

3. Rem adaptation

1. Flexble Adaptation Scheme (Alibaba Mobile Sales Team)

Flexible of Handtao solves the problem of 1px frame, and uses REM to realize the transition scheme of VW with equal scaling in different devices (maintenance has been stopped)

Application scenario: Display pages with many proportional zoom images or simple services

Core ideas:

// set 1rem = viewWidth / 10
function setRemUnit () {
    var rem = docEl.clientWidth / 10
    docEl.style.fontSize = rem + 'px'
}
setRemUnit();
Copy the code

The writing of fonts

document.documentElement.setAttribute('data-dpr', dpr)
Copy the code

Handle the side effects of 1px borders so that CSS writing can be fixed for different DPR sizes:

div { width: 1rem; Height: 0.4 rem; font-size: 12px; // fontSize} [data-dpr="2"] div {font: 24px; } [data-dpr="3"] div { font-size: 36px; }Copy the code
2. Media query + REM (Front-end team of netease)

The js version changes the font size of the HTML

$("html").css("font-size".document.documentElement.clientHeight/document.documentElement.clientWidth<1.5 ? (document.documentElement.clientHeight/603*312.5+"%") : (document.documentElement.clientWidth/375*312.5+"%"));
// For single-screen full-screen layout, zoom automatically in short screen
/ / $(" HTML "). The CSS (" the font - size ", the document. The documentElement. ClientWidth / 375 * 312.5 + "%");
// Use for long pages without scaling
Copy the code

CSS Media query Modify HTML font-size

Media query is not the final function, it exists only to prevent the js is not loaded before rendering the page, and after the JS loading, the page style changes too much and the page jumps, the experience is not good.

html {
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
  font-size: 62.5%;
}
html {
  font-size: 312.5%;
}
@media screen and (max-width: 359px) and (orientation: portrait) {
  html {
    font-size: 266.67%; }}@media screen and (min-width: 360px) and (max-width: 374px) and (orientation: portrait) {
  //(375/360) *312.5%=300%.html {
    font-size: 300%; }}@media screen and (min-width: 384px) and (max-width: 399px) and (orientation: portrait) {
  html {
    font-size: 320%; }}@media screen and (min-width: 400px) and (max-width: 413px) and (orientation: portrait) {
  html {
    font-size: 333.33%; }}@media screen and (min-width: 414px) and (max-width: 431px) and (orientation: portrait) {
  html {
    font-size: 345%; }}@media screen and (min-width: 432px) and (max-width: 479px) and (orientation: portrait) {
  html {
    font-size: 360%; }}@media screen and (min-width: 480px) and (max-width: 639px) and (orientation: portrait) {
  html {
    font-size: 400%; }}@media screen and (min-width: 640px) and (orientation: portrait) {
  html {
    font-size: 533.33%; }}Copy the code

The default font for the page is 16px. If we set the root font to 312.5%, it will be 16*312.5%=50px, which corresponds to 100px on the design sheet. The 100px elements on the design sheet will be written as 1REM in the style sheet

Disadvantages:

  • The font size value of the root element is strongly coupled, resulting in layout confusion when the system font is enlarged or shrunk. The second disadvantage: the HTML file header needs to insert a piece of JS code
  • Mobile terminal size adaptation has nothing to do with DPR. Except for Taobao scheme, other schemes still have the problem of 1px, but it also reduces the trouble of responding to different DPR devices

4. Vw/vh layout

Specific practice: You can use postCSS-px-to-viewport of WebPack Loader plug-in PostCSs-Loader to convert PX to VW

{
    loader: 'postcss-loader'.options: {
    plugins: () = >[
        require('autoprefixer') ({browsers: ['last 5 versions']}),require('postcss-px-to-viewport') ({viewportWidth: 375.// Viewport width (digit)
        viewportHeight: 1334.// Viewport height (number)
        unitPrecision: 3.// Set the reserved decimal number (digits)
        viewportUnit: 'vw'.// Set the unit to convert (string)
        selectorBlackList: ['.ignore'.'.hairlines'].// Class name not to be converted (array)
                minPixelValue: 1.// Set the minimum pixel value (number) to replace
                mediaQuery: false // Allow to convert px in media query (true/false)}})]Copy the code

5. Vw + rem layout

Method 1

How it works: Use VM to change HTML font size and REM to scale

// rem unit conversion: set75pxIt's just easy to calculate,750px-75px,640-64px,1080px-108px, and so on $vw_fontsize:75; // iPhone 6Size reference value for the root element size@function rem($px) {
     @return ($px / $vw_fontsize ) * 1rem; } // Use vw unit $vw_design for the root element size:750;
html {
    font-size: ($vw_fontsize / ($vw_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; / /}}bodyAlso increase the maximum and minimum width limits to avoid default100%Width of the block element followsbodyToo big too smallbody {
    max-width: 540px;
    min-width: 320px;
}
Copy the code

use

#app {
            width: 100%;
            .container {
                padding: rem(20) rem(20) rem(20) rem(20)
                .main {
                    width 100%}}}Copy the code
Method 2
  1. Set font size to 16 with pxtoREM conversion using 750 design (converted to 1x)

    Why is it 16? Because in the first step, we wrote it as a double graph, so if we don’t want to use REM, we can just get rid of pXtoREM, and we can just restore the code to PX. Right

  2. Add the font Settings for HTML to the front of the CSS. I used less

.font-size(@sizeValue:16) {
  @vw: 16 / 375 * 100;
  @result: @sizeValue / 16 * @vw;
  font-size: ~"@{result}vw";
}
html {
  .font-size(16);
}
html {
  @media screen and (max-width: 320px) {
    .font-size(16);
  }
  @media screen and (min-width: 480px) {
    .font-size(13); }}Copy the code

The essence of both VW and REM schemes is “equal scale scaling”, because both VW and REM are units of relative length, which can well meet this demand. The difference is that VW is 1% of the viewport width, while REM is the font size of the HTML element. After associating the font size of the HTML element with the viewport width, REM can simulate a VW layout

6. Flex flex layout

Regardless of the resolution of the mobile device, the height, width and position of the key elements remain the same, and only the container elements are scaled. The percentage layout, which eliminates the need to calculate percentages, works well on all screens

Features: text flow, control flexibility, picture scaling

Why use Flex layout

Float layout has side effects, if the child element is set to float, it will cause the parent element to collapse/can’t dynamically implement the adaptive layout/can’t set the padding margin properly/the previous element floats, the later element may be out of position, so the page becomes more and more complex to manage

Float layouts are unfriendly to mobile layouts, so flex is an elastic layout

Elements with a Flex layout are called Flex containers. All of its child elements automatically become container members

Flex container Properties
  • flex-direction
  • flex-wrap
  • flex-flow
  • justify-content
  • align-items
  • align-content
1. The flex – direction attribute

The flex-direction attribute determines the direction of the main axis (that is, the alignment of items).

.box {
  flex-direction: row | row-reverse | column | column-reverse; } // indicate that the main axis is horizontal and the starting point is at the left end. (Default) // The main axis is horizontal and the starting point is at the right end. // The main axis is vertical, and the starting point is on the top. // The main axis is vertical, and the starting point is down.Copy the code

2. The flex – wrap attributes

By default, projects are arranged on a line (also known as an “axis”). The flex-wrap property defines how to wrap a line if an axis does not fit.

.box{
  flex-wrap: nowrap | wrap | wrap-reverse; // No newline // newline, first line above. // Newline, first line below. }Copy the code
3. The flex – flow properties

The flex-flow property is a short form of the flex-direction and flex-wrap properties. The default value is Row Nowrap.

.box {
  flex-flow: <flex-direction> || <flex-wrap>;
}
Copy the code
4. Justify -content attribute (this is important and often used)

The context-content attribute defines the alignment of items on the main axis.

.box { justify-content: flex-start | flex-end | center | space-between | space-around; // Are left aligned (default) // right aligned // center aligned // both ends aligned, with equal spacing between items. // Each item is equally spaced. As a result, the spacing between items is twice as large as the spacing between items and the border. }Copy the code

5. Align -items property (this is also important. Also commonly used)

The align-items property defines how items are aligned on the cross axis.

.box { align-items: flex-start | flex-end | center | baseline | stretch; // In order is the starting point of the cross axis alignment. // Align the end of the cross axis. // Align the midpoint of the cross axis. // Baseline alignment of the first line of the project text. // If the project is not set to height or is set to auto, it will fill the entire container height (default)}Copy the code

6. The align – content attribute

The align-content property defines the alignment of multiple axes. This property has no effect if the project has only one axis.

.box { align-content: flex-start | flex-end | center | space-between | space-around | stretch; // In turn is aligned with the starting point of the cross axis. // Align with the end of the cross axis. // Align with the midpoint of the cross axis. // Align with the two ends of the cross axis, and the spacing between the axes is evenly distributed. // Both sides of each axis are equally spaced. Therefore, the spacing between axes is twice as large as the spacing between axes and borders. // The axis occupies the entire cross axis. (Default)}Copy the code

Project attributes
  • order
  • flex-grow
  • flex-shrink
  • flex-basis
  • flex
  • align-self
1. The order of attributes

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

.item {
  order: <integer>;
}
Copy the code

2. Flex-grow property (important)

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

If all projects have a flex-Grow attribute of 1, they divide the remaining space equally, if any. If one project has a flex-grow attribute of 2 and all the other projects are 1, the former takes up twice as much free space as the other items.

.item {
  flex-grow: <number>; /* default 0 */
}
Copy the code

3. The flex – the shrink properties

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.

If all projects have a Flex-shrink attribute of 1, they are scaled equally when space is insufficient. If the flex-shrink attribute is 0 for one project and 1 for all other projects, the former does not shrink when space is insufficient.

Note: Negative values do not apply to this property.

.item {
  flex-shrink: <number>; /* default 1 */
}

Copy the code

4. The flex-basis attribute (this is important, often used)

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.

It can be set to the same value as the width or height attribute (such as 350px), and the project will take up a fixed space.

5. Flex properties (most important)

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.

.item {// This property has two shortcut values: auto (1 1 auto) and None (0 0 auto). // It is recommended to use this attribute in preference to writing three separate attributes, as the browser will infer related values. flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ] }Copy the code
6. The align – self properties

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.

.item { align-self: auto | flex-start | flex-end | center | baseline | stretch; // Use align-items as the default}Copy the code

6.1 Flex Application

Commonly used Flex 1

Flex is short for flex-grow, flex-shrink, and Flex-basis

When flex is None, the evaluated value is 0. 0 auto

.div {
    flex-grow: 0;
    flex-shrink: 0;
    flex-basis: auto;
}   
Copy the code

If flex is auto, the calculated value is 1 1 AUTO

.div { flex-grow: 1; flex-shrink: 1; flex-basis: auto; }Copy the code

If flex is a non-negative number, the flex-grow number, flex-shrink set to 1, and flex-basis set to 0% (most commonly used).

.div { flex-grow: 1; Flex-shrink: 1; // Default flex-basis: 0%; / / the default}Copy the code

When flex is a length or percentage, the value is considered flex-basis, flex-grow is 1, and flex-shrink is 1

.div { flex-grow: 1; Default flex-shrink: 1; // Default flex-basis: 0%; // Get the value}Copy the code

When the value of flex is two non-negative digits, the value is regarded as flex-grow and flex-shrink respectively, and flex-basis is 0%

.div { flex-grow: 1; Flex-shrink: 1; // The second value to take is flex-basis: 0%; / / the default}Copy the code

When flex is a non-negative number and a length or percentage, it is treated as the value of flex-grow and flex-basis, respectively, and flex-shrink equals 1

.div { flex-grow: 1; Flex-shrink: 1; // Default flex-basis: 0%; // The second value to take}Copy the code

6.2 Common Flex layouts

Flex implements an equal layout
.box{
            height: 500px;
            display: flex;
}
.box div{
             height: 300px;
             border: 1px solid # 000000;
             flex: 1; / / here it isflex:1The use of}div class="box">
        <div> equal effect </div>
        <div> equal effect </div>
    </div>
Copy the code
Left fixed right adaptive
   .box {
            height: 500px;
            display: flex;
        }
        .box div {
            height: 300px;
            text-align: center;
        }
        .box div.right {
            flex: 1; // The right side is adaptiveborder: 1px solid # 000000;
        }
        .box div.left {
            border: 1px solid # 000000;
            flex-basis: 100px; // The left side is fixed with the highest priority} //html
    <div class="box">
        <div class="left"> < span style = "max-width: 100%; clear: bothdiv>
        <div class="right"> < span style = "max-width: 100%div>
    </div>
Copy the code

If the adaptive content of the edge exceeds the range, add min-width: 0 where the adaptive content is located. If the min-width is not set, the default is auto, which equals the adaptive width

Align vertically and horizontally
 .box {
            width: 100%;
            height: 300px;
            border: 1px solid purple;
            display: flex;
            justify-content: center;
            align-items: center;
        }
<div class="box"><p< / > centerp></div>
Copy the code

7. Mobile terminal adaptation of the molding scheme

  • Px + various layout means main /vx, Vx + media query as auxiliary scheme (if you do not use scaling can not use)

  • Set width=device-width viewPort in head

  • Use PX in CSS

  • Use flex layout in appropriate scenarios, or adapt with VW

  • Use media queries across device types (PC <-> mobile <-> tablet)

The next chapter will summarize some problems that web mobile end adaptation will often encounter, such as 1px line problems, wechat browser configuration safari adaptation how to adapt to iphonex landscape problem handling ~click event delay and penetration and other problems