The front ring is a mess. It’s true. But chaos also has the advantage of chaos, chaos leads to change, there is change only progress. Today, we will talk about the adaptation of mobile pages. Because for a front-end, every day and dealing with the page (H5 page), then the layout of the living is always indispensable, which will also face the adaptation of different terminals. I don’t know if you’re like me, but there’s always something more or less painful about layout. If so, I suggest you take some time to read through my bullshit below.

Flexible carries the mission

Flexible has been around for a few years now, saving many students from the adaptation problem of H5 page layout. And this scheme is a relatively mature scheme.














<! -- dpr = 1--> <meta name="viewport" content="initial-scale=scale,maximum-scale=scale,minimum-scale=scale,user-scalable=no"> <! -- DPR = 2--> <meta name="viewport" content="initial-scale=0.5,maximum-scale=0.5,minimum-scale=0.5,user-scalable=no"> <! -- dpr = 3--> <meta name="viewport" The content = "initial - scale = 0.3333333333, the maximum - scale = 0.3333333333, the minimum - scale = 0.3333333333, user - scalable = no" >Copy the code

So that the page up to the effect of zoom, but also the realization of the page adaptation function. There are three main ideas:

  • According to thedprTo modify the value ofviewportimplementation1pxThe line
  • According to thedprTo modify the value ofhtmlthefont-size, thus usingremAchieve geometric scaling
  • Use Hackremsimulationvwfeatures

There is about Flexible solution implementation adaptation, after the double 11 in 2015, we have done the technical document sharing in this aspect, interested students can move to read the article “Using Flexible to Achieve terminal adaptation of MOBILE TAOBAO H5 page”. Flexible solves a lot of problems with adapters, but it’s not the cure-all or the best. It has some problems, such as iframe references, which sometimes get us buried. In view of some of the shortcomings, some students have carried out relevant transformation of it, searching online can find the relevant scheme.

Times are changing and front-end technology is changing. Flexible or best solution? Is Flexible still necessary? We’ve been talking about this lately, and here’s to let you know that Flexible has fulfilled its historical mission. We can put down Flexible and embrace new changes. In the following content, I will share the new adaptation scheme that I have discussed recently. Maybe many team members have already started to use it. If there is anything wrong, I hope you can correct me. If you have a better plan, we hope to share and discuss together.

Serve first, talk later

First on the qr code:

You can scan the ABOVE TWO-DIMENSIONAL code using The Mobile App, Youku App, the browser of each terminal, UC browser, QQ browser, Safari browser and Chrome browser, and you can see the corresponding effect:

IPhone Effects

Partial Android Effects

Note: If scanning the qr code above does not have any effect, you can click here to open the online page and re-generate the QR code number that your device can recognize.

The Demo above tested the Top30 models. Currently unsupported:

brand model System version The resolution of the The screen size Hand for APP Youku APP Native browser QQ browser UC browser Chrome
huawei Mate9 Android7.0 1080 x 1920 5 inches Yes Yes No Yes Yes Yes
huawei Mate7 Android4.2 1080 x 1920 5.2 in. Yes Yes No Yes Yes Yes
meizu Mx4 (M460 mobile 4G) Android4.4.2 1152 x 1920 5.36 in. Yes No No Yes Yes Yes
Oppo R7007 Android4.3 1280 x 720 5 inches Yes No No Yes Yes No
samsung N9008 (Galaxy Note3) Android4.4.2 1080 x 1920 5.7 in. Yes No Yes Yes Yes Yes
asus ZenFone5(x86) Android4.3 720 x 280 5 inches No No No Yes No No

If the Top30 models are not in the list, you will see the effect shown above. As for the dare to use, that depends on the kiss. It takes courage to be the first to eat crab! (^_^)

Adaptation scheme

We have introduced the current support and effect of this scheme. A lot of crap, too. Let’s get to the point.

In mobile layout, we need to face two of the most important issues:

  • The adaptation of each terminal
  • Details for Retina display

Different terminals, we face a series of problems such as screen resolution, DPR, 1px, 2X graph. So the layout scheme is also targeted to solve these problems, but to solve these problems is no longer using Hack means to deal with, but directly using the native CSS technology to deal with.

Adapter terminal

The first solution is adaptation terminal. Recall that the previous Flexible solution was to emulate VW’s features in JavaScript, and by now VW is supported by many browsers, which means it’s straightforward to consider using VW units in our adaptive layout.

As is known to all, vw is based on the length of the Viewport window units, in this case, the Windows (Viewport) is the visual area of the browser, and the viewing area is the window. The innerWidth/window. The size of the innerHeight. Here’s a simple illustration:

Because Viewport involves a lot of knowledge, to introduce the clear knowledge of this aspect, need several articles to elaborate. @PPK has two articles detailing this knowledge. Chinese can be read here.

There are four viewport-related Units in CSS Values and Units Module Level 3: VW, VH, vmin, and vmax.

  • vw: short for Viewport’s width,1vwIs equal to thewindow.innerWidththe1%
  • vhAnd:vwSimilarly, short for Viewport’s height,1vhIs equal to thewindow.innerHeihgtthe1%
  • vmin:vminThe value of is currentvwandvhThe smaller value of
  • vmax:vmaxThe value of is currentvwandvhThe greater value of

If window.innerheight > window.innerWidth, vmin takes one hundredth of window.innerWidth. Vmax takes 1% of the window. InnerHeight.

Let’s use a picture. A picture is worth a thousand words:

Therefore, vw is boldly used in this scheme to replace the REM scaling scheme in the previous Flexible. Let’s get back to the actual business. At present, the width of the visual design draft is 750px. According to the above principle, 100VW = 750px, that is, 1vw = 7.5px. Then we can directly convert the px value on the design drawing into the corresponding VW value. The PostCSS plugin postcss-px-to-viewport allows you to write px directly in your code, for example:

[w-369]{
    width: 369px;
}

[w-369] h2 span {
    background: #FF5000;
    color: #fff;
    display: inline-block;
    border-radius: 4px;
    font-size: 20px;
    text-shadow: 0 2px 2px #FF5000;
    padding: 2px 5px;
    margin-right: 5px;
}
Copy the code

After compiling PostCSS, we need the code with VW:

[w - 369] {width: 49.2 vw; } [w-369] h2 span { background: #ff5000; color: #fff; display: inline-block; border-radius: .53333vw; Text-shadow: 0 0.26667vw 0.26667vw #ff5000; text-shadow: 0 0.26667vw 0.26667vw #ff5000; padding: .26667vw .66667vw; < span style = "max-width: 100%; box-sizing: border-box! Important; margin-right: .66667vw; }Copy the code

In practice, you can configure the parameters of this plug-in:

"postcss-px-to-viewport": {
    viewportWidth: 750,
    viewportHeight: 1334,
    unitPrecision: 5,
    viewportUnit: 'vw',
    selectorBlackList: [],
    minPixelValue: 1,
    mediaQuery: false
}
Copy the code

If your design is 1125px instead of 750px, then you can change the value of vewportWidth. For details about the plug-in, you can read its official usage documentation.

The above solved the conversion calculation of PX to VW. So where can VW be used to fit our pages? According to relevant tests:

  • Container fit can be usedvw
  • Text adaptation can be usedvw
  • Is greater than1pxBorders, rounded corners, and shadows can all be usedvw
  • Inner and outer distances can be usedvw

There is another detail that needs to be specially proposed. For example, we have a design like this:

If we directly use:

[w-188-246] {
    width: 188px;
}
[w-187-246]{
    width: 187px
}
Copy the code

The end result is that the height of the [W-187-246] container is less than the height of the [W-188-246] container. At this point we need to take into account the aspect ratio of the container scaling. There are many schemes in this respect, but I still recommend to deal with it as a tool. Here I recommend a PostCSS plug-in postCSS-aspx-ratio -mini written by @ Xian sister. This plugin is very simple to use and does not require any configuration. You just need to install it locally. Use as follows:

[aspectratio] {
    position: relative;
}
[aspectratio]::before {
    content: '';
    display: block;
    width: 1px;
    margin-left: -1px;
    height: 0;
}

[aspectratio-content] {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}
[aspectratio][aspect-ratio="188/246"]{
    aspect-ratio: '188:246';
}
Copy the code

Compile:

[aspectratio] [aspect - thewire = "188/246"] : before {padding - top: 130.85106382978725%; }Copy the code

This can be perfect to achieve the effect of the aspect ratio. The principle of this aspect is not elaborated here. If you are interested, you can read the article sorted out earlier:

  • The CSS implements the aspect ratio
  • Container aspect ratio
  • How do you implement aspect ratios on the Web
  • To achieve accurate fluid typesetting principle

The PostCSS plugin is just an interim step, but in the future we can use aspect-ratio properties directly in CSS to implement aspect ratios.

To solve1pxplan

As mentioned earlier, it is not recommended to convert 1px to vw units, but with Retina, we always have to deal with the 1px problem. In the article on 1px Solutions for Retina, there are several solutions for 1px. In this case, I personally recommend another 1px solution. Use PostCSS plugin to solve 1px postCSs-write-svg.

With postCSs-write-svg, you can use either border-image or background-image. Such as:

@svg 1px-border {
    height: 2px;
    @rect {
        fill: var(--color, black);
        width: 100%;
        height: 50%;
    }
}
.example {
    border: 1px solid transparent;
    border-image: svg(1px-border param(--color #00b1ff)) 2 2 stretch;
}
Copy the code

PostCSS will automatically compile your CSS for you:

.example { border: 1px solid transparent; border-image: url("data:image/svg+xml; charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='2px'%3E%3Crect fill='%2300b1ff' width='100%25' height='50%25'/%3E%3C/svg%3E") 2 2 stretch; }Copy the code

Using PostCSS plug-ins is easier and more convenient than we modify images.

In addition to the border-image method shown above, background-image can also be used to implement. Such as:

@svg square {
    @rect {
        fill: var(--color, black);
        width: 100%;
        height: 100%;
    }
}

#example {
    background: white svg(square param(--color #00b1ff));
}
Copy the code

To compile:

#example { background: white url("data:image/svg+xml; charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3Crect fill='%2300b1ff' width='100%25' height='100%25'/%3E%3C/svg%3E"); }Copy the code

This solution is simple and easy to use, which is what I need. After the current test, it can basically meet the requirements I need. But don’t forget to add to :

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

What is described above is the technical points used in this adaptation scheme, and a simple summary:

  • usevwTo achieve page adaptation, and through the PostCSS plug-inpostcss-px-to-viewportthepxConverted tovw. The nice thing about this is that we don’t have to do any calculations when we’re doing this, you just have to follow the designpxunit
  • In order to better achieve the aspect ratio, especially forimg,vedioandiframeElement via the PostCSS pluginpostcss-aspect-ratio-miniTo achieve, in actual use, just need to write the corresponding width and height in
  • In order to solve the1pxUsing the PostCSS pluginpostcss-write-svg, automatically generatedborder-imageorbackground-imagePictures of the

There are several PostCSS plugins here, and there are a lot of good PostCSS plugins out there that can help us solve a lot of problems. If you have never read about PostCSS before, I suggest you take some time to learn about it. There are some articles about PostCSS on W3cplus. If you want to learn about PostCSS systematically, you are recommended to purchase the book In Depth PostCSS Web Design:

down-cycled

As mentioned at the beginning, several models of T30 do not support VW adaptation so far. So what if the business needs it? There are two ways to downgrade:

  • CSS HoudiniThrough:CSS HoudiniforvwDo the processing, callCSS Typed OM Level1To provide theCSSUnitValue API.
  • CSS Polyfill: The corresponding Polyfill will be used for corresponding processing. Currently, it is targeted atvwPolyfill units mainly include:vminpoly,Viewport Units Buggyfill,vunits.jsandModernizr. Personal recommendationViewport Units Buggyfill

Shortcomings of Viewport

Using VW for adaptation is not all good without any disadvantages. Some of the details are flawed. For example, when the container uses VW unit and the margin uses PX unit, it is easy to cause the overall width to exceed 100vw, thus affecting the layout effect. For such a phenomenon, we can use relevant technology to avoid. For example, change margin to padding and use box-sizing. However, this is not the best solution. In the future, when vw and PX are used together, calc() can be used together with browser or application Webview support for calc().

Another point is that when PX is converted into VW units, there will still be a certain pixel difference. After all, in many cases, it cannot be completely divisible.

So far, I’ve found two weaknesses. Maybe in the later use, there will be some other pit. It is true that any scheme gets stronger the more it stumbles. I hope the students who like this adaptation plan will step on the pit with me to make it more perfect.

How do I know if my application supports it

Although the examples in this article are tested in many aspects. However, many students still worry about whether their APP supports the scheme, and dare not try or use it. There’s no need to worry. You can scan the following QR code with your device or app:

When the page has run the tests, locate the Values and Units list item:

If vw is green, your device or application supports the solution. Otherwise, it is not supported. You can also keep an eye out for cSS3Test updates, which will update the test code according to the relevant specifications, so that you can quickly learn which attributes to use boldly.

conclusion

H5 page fit is always a pain in the neck, in fact the layout of the page is always a pain in the neck. However, technology is constantly innovating. We can keep our attention to new technologies and try to apply these new features to actual projects. Only in this way, our solutions to problems will be more and more perfect.

Until this article is written, although there are still one or two models that do not support VW, it does not affect our use. Only when you keep trying can you make progress. Here, I hope we can boldly try to make the scheme more perfect together. If you have better suggestions, or if you’ve stepped on any potholes, feel free to share them in the comments below, or email me to discuss them.

The desert

Illustration of CSS3: Core technologies and case studies

If you need to reprint, please indicate the source: www.w3cplus.com/css/vw-for-…