On mobile, though, most browser kernels are WebKit, and most of them support all the syntax of CSS3. However, because there are different screen sizes, different resolutions, or you need to consider horizontal and vertical screens, or all sorts of mobile compatibility issues. You’re going to have to figure out how to perform on different phones in different situations, so you need a mobile adaptation that works right out of the box.
First, basic knowledge
If you want to do something well, you must sharpen your tools first. Before introducing adaptation schemes in detail, we will learn relevant knowledge points in this chapter to facilitate the direct reception of subsequent adaptation schemes.
1.1. Responsive design – Pixels
Pixel units include device pixel, logical pixel, and CSS pixel.
1.1.1 Device pixel and device resolution
Device Pixels, also known as physical pixels, are the actual pixels on a display, and the size of each pixel is an inherent property of the screen that doesn’t change when it leaves the factory. The device resolution describes how many device pixels are the width and height of the display. For example, a common display resolution is 1920 * 1080. Device pixels and device resolution are managed by the operating system, and the browser does not and does not need to know the size of the device resolution, which is calculated primarily from the logical resolution ratio (described in the next section).
1.1.2 Device independent pixel and logical resolution
Device Independent Pixels is a unit of pixels defined by the operating system. An application informs the operating system of device independent pixels. The operating system converts device independent pixels into device pixels to control the actual physical pixels on the screen. Why define such a unit between application and device pixels? Why shouldn’t applications use device pixels directly? For example, a font with a height of 12 device pixels used to be displayed on the 1280×720 device resolution screen is now displayed on the 2560 ×1440 device resolution screen. In order to obtain the original size, 24 device pixels are required. If the application directly uses device pixels, Writing an application becomes very difficult and requires writing application logic: fonts are 12 device pixels high on some screens and 24 device pixels high on others. So the operating system defines a unit: device-independent pixels. The operating system guarantees that dimensions defined with device-independent pixels (hence the name device-independent pixels) will be displayed at the appropriate size regardless of screen parameters. How does the operating system do this? For those screens with high pixel density, divide multiple device pixels into one logical pixel. How many device pixels are divided into a logical pixel is up to the operating system. For the example above, “the original height is 12 equipment pixel font, height is 24 now device pixels can be the same size”, the operating system will be a logical pixel is defined as 2 * 2 pixels, thus equipment independent pixel size do not need to change, and no matter on the new and old equipment, according to the size of the roughly the same.
Monitor manufacturers and operating system manufacturers do research to determine the ratio of device-independent pixels to device-specific pixels. As a general rule, the higher the pixel density of a screen, the more device pixels are required to display a device-independent pixel.
The logical resolution is expressed in the width and height of the screen (in device-independent pixels), and we change the device-independent pixel size through the resolution Settings of the operating system. For example, if the device resolution of the screen is 19201200 (in device pixels), we can set the logical resolution to 1280*800 (in device-independent pixels) at the current resolution. The number of horizontal and vertical device pixels is exactly 1.5 times the number of individual device pixels. This also means that the side length of the device’s individual pixels is 1.5 times the side length of the device’s pixels.
1.1.3 CSS Pixels
Use px in CSS to refer to CSS pixels, such as Width: 128px. CSS pixel sizes are easy to change. When we zoom in and out of a page, the number of CSS pixels in an element does not change, only the size of each CSS pixel changes. This means that an element with width: 128px will still be 128 CSS pixels wide when scaled 200%, but each CSS pixel will be twice as wide and tall. If the original element width was 128 device independent pixels, then the element width will be 256 device independent pixels after scaling 200%.
(1) The relationship between CSS pixels and device independent pixels
- The scaling ratio is CSS pixel edge length/device-independent pixel edge length;
- At 100% zoom, one CSS pixel is equal to one device-independent pixel;
- At 200% zoom, one CSS pixel is equal to (2 x 2) device-independent pixels;
(2) The relationship between CSS pixels and device pixels
DevicePixelRatio devicePixelRatio, devicePixelRatio = (on a line of the same length) number of device pixels/number of CSS pixels. This ratio is also equivalent to CSS pixel edge length/device pixel edge length. For example, devicePixelRatio = 2 indicates that in a line of the same length, the number of device pixels is twice that of the CSS pixels. Therefore, the side length of CSS pixels is twice that of the device pixels. Scaling causes the edge length of CSS pixels to change, which causes window.DevicepixelRatio to change!
1.2. Responsive design – ViewPort
Viewport represents the viewport area of the browser, the part of the browser that displays the web page. There are three viewports: Layout ViewPort, Visual ViewPort and Ideal ViewPort. We will introduce three viewports respectively.
1.2.1, layout viewport
A Layout ViewPort is an area of the web layout that is the parent container of HTML elements. As long as you do not modify the width of the elements in the CSS, the width of the elements will fill the layout ViewPort. Many times a browser window does not have the ability to view a Layout viewPort in its entirety, but it has already been loaded. This is when the scroll bar appears and you need to scroll through the rest of the Layout ViewPort. Layout ViewPort uses CSS pixels to measure dimensions and does not change when zooming or adjusting the browser window. Zooming and adjusting the browser window changes only the Visual ViewPort.
In desktop browsers, the Layout Viewport width is equal to the width of the content window at 100% zoom. (You’ll almost never see a horizontal scroll bar on a computer unless you zoom.) But on mobile, a Layout Viewport doesn’t necessarily equal the size of the content window at 100% zoom. When you use your phone to browse large web pages that are not designed to be responsive, you can only browse one part of the page at a time and then swipe through the rest. This means that the entire web page Viewport has been loaded, but you need to view it in sections.
1.2.2, visual viewport
A visual ViewPort is a visual viewport that displays only part of a layout viewport on a web page. A Visual ViewPort is like a camera, and a layout ViewPort is like a piece of paper. Whichever part of the paper you point the camera at, you see. You can change the size of the camera area (adjust the size of the browser window) and the distance (adjust the zoom) of the camera. You can change the Visual ViewPort, but the Layout ViewPort remains the same.
1.2.3, ideal viewport
Ideal ViewPort is the ideal viewport. Different devices have their own ideal Viewport. The width of ideal Viewport is equal to the screen width of mobile devices, so it is the most suitable viewport for mobile devices. Simply set the width of an element in CSS to the ideal Viewport width (in px) and the element will be the width of the device screen (100% width). 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.
1.2.4 Use meta tags to control viewPort
The default viewPort for mobile devices is a Layout ViewPort, which is wider than the screen, but for mobile site development we need the Ideal ViewPort. So how do you get the Ideal ViewPort? The most common tags we see when developing h5 pages are shown below
<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = 0">
Copy the code
This meta tag makes the width of the current viewPort equal to the width of the device, and does not allow the user to manually scale. If you don’t, you’ll use a default viewPort that is wider than the screen, which means a horizontal scroll bar. The meanings of the related attributes are shown below
width | Set layout ViewPort width to a positive integer or string “width-device” |
---|---|
height | Sets the initial zoom value of the page to a number, possibly with a decimal |
initial-scale | The minimum zoom value allowed to the user is a number, which can be a decimal |
minimum-scale | The maximum zoom value allowed to the user is a number, which can be a decimal |
maximum-scale | Set the height of the Layout ViewPort. This property is not important to us and is rarely used |
user-scalable | Whether to allow users to zoom in and out. The value is “no” or “yes”, where “no” means “no” and “yes” means “yes” |
2. Program selection
Some representative adaptation schemes appeared in different periods of the historical development of the front trend, and the following are briefly introduced.
2.1. Use the CSS media Query @media
Css-based media query attribute @media Write CSS properties of different sizes for mobile devices with different screen sizes, as shown in the following example. Although this method can solve the problem of mobile device adaptation to a certain extent, we can also see that it has the following problems, so it has been almost eliminated by the historical trend.
- All the elements on the page have to be defined at different sizes in different @media, which is a bit expensive;
- If you had one more screen size, you would have to write another @media query block.
@media only screen and (min-width: 375px) {
.logo {
width : 62.5 px.; }}@media only screen and (min-width: 360px) {
.logo {
width : 60px; }}@media only screen and (min-width: 320px) {
.logo {
width : 53.3333 px.; }}Copy the code
2.2 use REM units
Rem (font size of the root Element) is the unit of font size relative to the root element. If we set the FONT size of the HTML to 16px, if we need to set the font size of the element to 16px, we write 1rem. However, it still has to use the @media attribute to set different font sizes for devices of different sizes. Compared with the previous scheme, it can reduce the cost of repeatedly writing the same attribute, as shown in the following simple example. We can also see the following problems with this scheme:
- Different sizes require multiple @media;
- All of the places that involve rem use require calling the calc() method, which is also cumbersome;
@media only screen and (min-width: 375px) {
html {
font-size : 375px; }}@media only screen and (min-width: 360px) {
html {
font-size : 360px; }}@media only screen and (min-width: 320px) {
html {
font-size : 320px; }} // Define method: calc@function calc($val){
@return $val / 1080;
}
.logo{
width : calc(180rem);
}
Copy the code
2.3 Flexible adaptation scheme
In rem scheme for improvement, we can use JS to dynamically set the root font, the typical representative of this scheme is flexible adaptation scheme.
2.3.1 Use REM to simulate VW for a variety of screen sizes
Its core code is shown below
// set 1rem = viewWidth / 10
function setRemUnit () {
var rem = docEl.clientWidth / 10
docEl.style.fontSize = rem + 'px'
}
setRemUnit();
Copy the code
In the above code, the FONT size of the HTML node is set to 1/10 of the page clientWidth(layout viewport), which means that 1rem is equal to 1/10 of the page layout viewport, which means that the REST of the REM is calculated in proportion to the page.
2.3.2 Control the width and scale values of viewport for high-power screen display
Set the width of the viewport to device-width, and change the default width of the browser viewport (layout viewport and visual viewport) to the desired viewport width so that the user can see the full layout viewport content within the desired viewport. Set the viewport’s initial-scale, maximum-scale and minimum-scale values equally, so that 1 physical pixel =1 CSS pixel is suitable for high-magnification display (this is where the well-known “1px problem” is avoid).
var metaEL= doc.querySelector('meta[name="viewport"]');
var dpr = window.devicePixelRatio;
var scale = 1 / dpr
metaEl.setAttribute('content'.'width=device-width, initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no');
Copy the code
2.3.3 Flexible defects
There’s no denying that Flexible helped thousands of developers at a time when compatibility wasn’t friendly, but the solution has its own problems.
- Due to its scaling, the style of the video player for the video TAB varies greatly between DPR devices;
- If you have studied the lib-flexible source code, then you must know that lib-flexible for Android phone special processing, that is: all press DPR = 1 processing;
if (isIPhone) {
// On iOS, use 2x for 2 and 3 screens, and 1x for the rest
if (devicePixelRatio >= 3&& (! dpr || dpr >=3)) {
dpr = 3;
} else if (devicePixelRatio >= 2&& (! dpr || dpr >=2)){
dpr = 2;
} else {
dpr = 1; }}else {
// For other devices, use the same 1 times scheme
dpr = 1;
}
Copy the code
- The responsive layout of @media is no longer compatible, because the size query statement involved in the @media syntax is based on the physical pixels of the current device and the flexible layout theory (i.e. the scale value of the viewport of different DPR devices is equal to the scale value, Therefore, responsive layout will not work properly when the viewport size is proportionally scaled;
In fact, flexible solution is to simulate the viewport function, but with the development of browsers and compatibility enhancement, Viewport has been compatible with most mainstream browsers, and flexible solution has its own problems, so it has almost been out of the historical trend. To quote lib-Flexible’s Github home page:
Since viewPort units are compatible with many browsers, lib-flexible is a transition solution that can be abandoned, and there are problems with both current and previous versions. It is recommended that you start using viewPort instead.
2.4 Viewport adaptation scheme
Because viewport unit is compatible with many browsers, mobile terminal adaptation schemes based on Viewport are adopted by various factory teams at present.
Vw, as a layout unit, fundamentally solves the problem of screen adaptation of different sizes from the bottom, because the percentage of each screen is fixed, predictable and controllable. Viewport concepts are as follows:
- Vw: short for viewport’s width. 1vw is equal to 1% of window.innerWidth;
- Vh: similar to vw, short for viewport’s height. 1vh equals 1% of window. InnerHeihgt;
- Vmin: The value of vmin is the smaller value of the current VW and VH;
- Vmax: The value of vmax is the larger value of the current VW and VH;
Let’s say the width of the visual is 750px, and a font size is 75px, then we can write the CSS properties as follows, no extra js Settings, no need to zoom the screen, etc.
.logo {
font-size: 10vw; // 1vw = 750px * 1% = 7.5 px.
}
Copy the code
2.4.1. Set the Meta tag
Set the MATA tag in the HTML header as shown below so that the width of the current ViewPort is equal to the width of the device without allowing the user to manually zoom in.
<meta name="viewport" content="Width = device - width, initial - scale = 1.0, the maximum - scale = 1.0, user - scalable = 0">
Copy the code
2.4.2 Px is automatically converted to VW
Designers usually give visual drafts with widths of 375px or 750px. If we adopt VW scheme, we need to convert the corresponding element size unit PX into VW unit. This is something that affects development efficiency (manually converting PX to VW is required) and prevents subsequent code maintenance (CSS code with vw units is not as intuitive as PX); The postCSs-px-to-viewport plugin is available to automatically convert PX to VW.
(1) Install the plug-in
npm install postcss-px-to-viewport --save-dev
Copy the code
(2) WebPack configuration
The official website uses GLUP for configuration, but in our project template, we use WebPack for configuration of postCSS plug-in and related style plug-in, so we use WebPack for configuration and use, without additional introduction of gulP compilation. The webpack configuration is as follows, and the meaning of each attribute is commented:
module.exports = {
plugins: {
// ...
'postcss-px-to-viewport': {
// options
unitToConvert: 'px'.// The unit to convert, default is "px"
viewportWidth: 750.// The window width of the design draft
unitPrecision: 5.// The precision retained after the unit conversion
propList: [The '*'.'! font-size'].// List of attributes that can be converted to vw
viewportUnit: 'vw'.// The window unit you want to use
fontViewportUnit: 'vw'.// The window unit used by the font
selectorBlackList: [].// CSS selectors that need to be ignored will not be converted to window units, using the original units such as PX
minPixelValue: 1.// Set the minimum conversion value. If it is 1, only values greater than 1 will be converted
mediaQuery: false.// Whether the unit in the media query needs to be converted
replace: true.// Whether to replace the attribute value directly without adding the standby attribute
exclude: undefined.// Ignore files under certain folders or specific files, such as files under 'node_modules'
include: /\/src\//.// If include is set, only matching files will be converted
landscape: false.// Whether to add media query criteria generated by landscapeWidth
landscapeUnit: 'vw'.// The unit used in landscape
landscapeWidth: 1125.// Width of window to use in landscape,}}};Copy the code
The function of relevant configuration attributes is clear through annotations. The point that needs to be emphasized is the propList attribute. We configured font-size without converting VW, that is to say, the font size is the same under different screen sizes of mobile phones. Whether font size needs to be adapted to the screen size, or how to do so, has long been a controversial topic. Considering that our mobile terminal does not have the requirements of tablet and we have consulted the opinions of the team business designer, we make the default configuration of the template above. Of course, if your vision requires your project to make font size adaptation, modify the configuration of the propList property.
(3) Effect display We conducted the following CSS coding in the project code:
.hello {
color: # 333;
font-size: 28px;
}
Copy the code
When we start the project, we can see that the browser rendered the page, postcss-px-to-viewport has done the px- > vw conversion for us; As follows:
2.4.3 Annotate attributes that do not need to be transformed
Ignoring the action, postCSS-px-to-viewPort is used to annotate the CSS properties that do not need to be converted.
- /* px-to-viewport-ignore-next */ — > The next line is not converted.
- /* px-to-viewport-ignore */ — > The current line is not converted
/* example input: */
.class {
/* px-to-viewport-ignore-next */
width: 10px;
padding: 10px;
height: 10px; /* px-to-viewport-ignore */
}
/* example output: */
.class {
width: 10px;
padding: 3.125 vw;
height: 10px;
}
Copy the code
2.4.4 Reserved pits for Retina display
Considering the Retina screen scene, there may be a demand for the image’s high-definition degree, 1px and other scenes, so we reserve the pit position for judging the Retina screen. Related schemes are as follows: DPR judgment in the HTML page of the entry, and data-DPR setting; Then in the CSS file of the project you can write different style classes according to the value of data-DPR according to the different DPR;
(1) index. HTML file
/ / index. The HTML file
const dpr = devicePixelRatio >= 3? 3: devicePixelRatio >= 2? 2: 1;
document.documentElement.setAttribute('data-dpr', dpr);
Copy the code
(2) Style file
[data-dpr="1"] .hello {
background-image: url([email protected]);
[data-dpr="2"] .hello {
background-image: url([email protected]);
}
[data-dpr="3"] .hello {
background-image: url([email protected]);
}
Copy the code
3. Best practices for several specific scenarios
3.1. Inline style scenarios
Postcss-px-to-viewport does not convert px units when you need to write inline style code. You need to calculate vw manually.
Best practice: It is better practice to keep JS and CSS separate by adding, modifying, and deleting classnames to handle such scenarios rather than directly manipulating inline styles.
3.2, 1px questions
The 1px line for Retina display is a commonplace problem. Compared with ordinary display, the 1px line for Retina display is thicker and lacks aesthetic design. For visual designers, 1px means device pixel 1px. If we write CSS size 1px, it will equal 2px device pixels at DPR = 2, and 3px device pixels at DPR = 3. So for scenarios that require processing 1px, we’ll do a special processing. The following describes the common methods
3.2.1, transform: scale (0.5)
You can scale the X and Y axes using Transform: Scale (0.5), as shown in the following example
.class1 {
height: 1px;
transform: scaleY(0.5);
}
Copy the code
The advantage is that it is easy to write, but it can be tricky to implement four borders, and if there is nesting, it will affect the contained elements, so use a combination of :before and :after.
3.2.2, transform: scale(0.5) + :before / :after
This method can be used for scenarios such as the 1px border on the left, right, and top of the label, as well as scenarios with nested elements, as shown in the following example
.calss1 {
position: relative;
&::after {
content:"";
position: absolute;
bottom:0px;
left:0px;
right:0px;
border-top:1px solid # 666;
transform: scaleY(0.5); }}Copy the code
3.2.3, box – shadow
Use CSS for shadow processing to simulate the border, as shown in the following example, a line at the bottom, the disadvantage is that the shadow is not good-looking.
.class1 {
box-shadow: 0 1px 1px -1px rgba(0.0.0.0.5);
}
Copy the code
3.2.4, other
There are also the following ways to deal with 1px problems, but not recommended, you can understand
- Viewport: Shrinks the page;
- Border-image: Cut a 1px image to simulate;
- Background-image: Cut a 1px image to simulate;
- Linear-gradient: Move 1px line through linear gradient;
- SVG: Vector-based graphics (SVG) scales with different device screen features.
3.3. The problem of picture hd
Problems with picture hd:
- Images that work on a retina display tend to be blurry;
- On a normal screen, images lack chromatic aberration, lack sharpness, and waste bandwidth;
Therefore, if scenes with high requirements for performance and beauty need to be differentiated according to DPR, we reserve A DPR solution for Retina screen in the viewport adaptation scheme of the article, and the relevant CSS is written as follows:
[data-dpr="1"] .hello {
background-image: url([email protected]);
[data-dpr="2"] .hello {
background-image: url([email protected]);
}
[data-dpr="3"] .hello {
background-image: url([email protected]);
}
Copy the code
IPhoneX adaptation scheme
The iPhoneX removed the physical button and replaced it with a small black bar at the bottom, a change that resulted in awkward screen adaptation issues for web pages. For the web page, the top (bangs) of the adaptation problem browser has done, so we only need to pay attention to the bottom and the small black bar adaptation problem (that is, the common bottom navigation, return to the top and other elements relative to the bottom fixed positioning). For example, some buttons that need to be stuck to the bottom, and tabbars and pop-ups that call up at the bottom, will be blocked by small black bars on the iphoneX, or white gaps on the page. The following figure shows the screenshot before and after processing
4.1. Several new knowledge needs to be learned before adaptation
4.1.1. Security Zone
The safe area refers to a visual window range. Contents in the safe area are not affected by corners, fringe sensor housing and Home Indicator, as shown in the blue area below:
In other words, we have to make sure that the visible and actionable areas of the page are within the safe zone for good adaptation. For more details, refer to Human Interface Guidelines-iphoneX
4.1.2, the viewport – fit
IOS11 new feature, apple in order to adapt iPhoneX to the existing viewport meta tag extension, used to set the layout of the web page in the visual window, can set three values.
- Contain: a visual window that contains everything on the web
- Cover: The content of the web page completely covers the visible window (right)
- Auto: indicates the default value, which is the same as the contain
Note: viewport-fit=cover is the key step to contain an iPhoneX. For more details, see the documentation: viewport-fit-Descriptor
4.1.3, env() and constant()
New in iOS11, Webkit is a CSS function for setting the distance between a security zone and a boundary. There are four predefined variables:
- Safe-area-inset-left: indicates the distance between the security zone and the left boundary
- Safe-area-inset-right: indicates the distance between the security zone and the right boundary
- Safe-area-inset-top: indicates the distance between the security zone and the top boundary
- Safe-area-inset-bottom: indicates the distance between the security zone and the bottom boundary
Here we only need to focus on the safe-area-inset-bottom variable because it corresponds to the height of the little black bar.
Note: Env () does not contain any information if it contains viewport-fit=cover. Browsers that do not support env() will ignore it.
It’s important to note that constant() is not available after iOS11.2, but we still need to do backward compatibility, like this:
padding-bottom: constant(safe-area-inset-bottom); /* Compatible with iOS < 11.2 */
padding-bottom: env(safe-area-inset-bottom); /* Compatible with iOS >= 11.2 */
Copy the code
Note that env() and constant() need to be in the same order. For more information, please refer to this document: Designing Websites for iPhone X
4.2 Adaptation steps
4.2.1. Set the layout of the web page in the visual window
New viweport-fit attribute (viweport-fit =cover, env())
<meta name="viewport" content="width=device-width, viewport-fit=cover">
Copy the code
4.2.2 Fixed is fully adapted to the scene of bottom-sucking elements
You can extend the height by adding an inner margin:
{
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);
}
Copy the code
Or override the original height by calculating the function calc:
{
height: calc(60px(Assumed value) +constant(safe-area-inset-bottom));
height: calc(60px(Assumed value) +env(safe-area-inset-bottom));
}
Copy the code
Note that this scheme requires the bottom strip to have a background color, because part of the background of the expansion is to follow the outer container, otherwise there will be hollow out.
Alternatively, you can add a new element (an empty color block, mainly for the height of the small black bar), and then the bottom element can be adjusted without changing its height, like this:
{
margin-bottom: constant(safe-area-inset-bottom);
margin-bottom: env(safe-area-inset-bottom);
}
Copy the code
Empty color block:
{
position: fixed;
bottom: 0;
width: 100%;
height: constant(safe-area-inset-bottom);
height: env(safe-area-inset-bottom);
background-color: #fff;
}
Copy the code
4.2.3 Fixed is not completely adapted to the scene of bottom-sucking elements
Like this, only the position needs to be adjusted upwards, which can be handled only by the bottom margin margin-bottom
{
margin-bottom: constant(safe-area-inset-bottom);
margin-bottom: env(safe-area-inset-bottom);
}
Copy the code
Alternatively, you can override the original bottom value by calculating the function calc:
{
bottom: calc(50px(Assumed value) +constant(safe-area-inset-bottom));
bottom: calc(50px(Assumed value) +env(safe-area-inset-bottom));
}
Copy the code
V. VW compatibility scheme
Android 4.4 and iOS 8 and below have some compatibility issues (ps: almost dead, you can count the percentage of your users using the OS version), but the community provides a compatibility solution, which is buggyFill in Viewport: Viewport Units Buggyfill, which can be viewed on github. We have also done the corresponding practice, but considering the performance, our project template will not be introduced, interested students can check the following practice summary;
5.1 Viewport Units Buggyfill is introduced
Viewport-units-buggyfill consists of two JavaScript files: viewport-units-buggyfill. Js and viewPort-units-buggyfill. Hacks.js. You just need to include these two files in your HTML file, such as index.html in the React project;
<script src="/ / g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js, viewport - units - bugg yfill.min.js"></script>
Copy the code
Second, call viewport-units-BuggyFill in the HTML file, for example:
<script>
window.onload = function () {
window.viewportUnitsBuggyfill.init({
hacks: window.viewportUnitsBuggyfillHacks
});
}
</script>
Copy the code
But in order for Viewport Units Buggyfill to work, we must add content where we used the Viewport Units (vw, VH, vmin, or vmax) in our style file, as follows:
.my-viewport-units-using-thingie {
width: 50vmin;
height: 50vmax;
top: calc(50vh - 100px);
left: calc(50vw - 100px);
/* hack to engage viewport-units-buggyfill */
content: 'viewport-units-buggyfill; width: 50vmin; height: 50vmax; top: calc(50vh - 100px); left: calc(50vw - 100px); ';
}
Copy the code
5.2. Postcss-viewport-units are introduced
In step 1, we introduced the content attribute, which was very inefficient. Fortunately, the community provides a plugin for postCSS-Viewport-Units to automatically process the content:
5.2.1 Installation and configuration of postCSS-viewport-units
To install the postCSS-viewport-units plug-in, run the following command:
tnpm i postcss-viewport-units --save-dev
Copy the code
Make the corresponding plug-in import configuration in our project configuration file webpack.config.js:
{
loader: 'postcss-loader'.options: {
ident: 'postcss'.plugins: () = > [
// We add the configuration
require('postcss-viewport-units')],sourceMap: isProductionEnv,
},
},
Copy the code
5.2.2 Effect display
In the project code, we encode as follows:
.hello {
color: # 333;
font-size: 28px;
}
Copy the code
On the page shown, postCSS-ViewPort-Units has added the Content property for us; As follows:
Blog github address: github.com/fengshi123/… , a summary of all the author’s blog, welcome to follow and star ~
Vi. References:
- Responsive design – Understand device pixels, device independent pixels, and CSS pixels
- An in-depth understanding of viewport for mobile front-end development
- Use Flexible to achieve terminal adaptation of H5 page
- VW: It’s time to abandon the REM layout
- lib-flexible
- postcss-px-to-viewport
- Web page for iPhoneX