当前位置:网站首页>Comparison of common layout solutions (media query, percentage, REM and vw/vh)
Comparison of common layout solutions (media query, percentage, REM and vw/vh)
2022-06-24 06:10:00 【User 8639654】
Brief introduction : In front end development , Static web pages usually need to adapt to different resolution devices , Common adaptive solutions include media queries 、 percentage 、rem and vw/vh etc. . This paper starts from px Unit departure , Analysis of the px Deficiencies in mobile terminal layout , Then several different adaptive solutions are introduced .
- px And viewports
- Media query
- percentage
- Adaptive scene rem Solution
- adopt vw/vh To achieve adaptive
One 、px And viewports
In static web pages , We often use pixels (px) As a unit , To describe the width, height and positioning information of an element . stay pc End , It is commonly believed css in ,1px The real length represented is fixed .
that ,px It's really a device independent , Is it of the same fixed size as the unit of length meters and decimeters ?
The answer is No , The picture below 1.1 Sum graph 1.2 respectively pc Display results under the end and mobile end , In the web page we set up font-size Uniform for 16px.
chart 1.1 pc Lower end font-size by 16px The display result of
chart 1.2 Under the mobile terminal font-size by 16px The display result of
It can be seen from the comparison of the above two pictures , All the fonts are 16px, Clearly in pc The text in the end is displayed normally , On the mobile end, the text is very small , I can hardly see , Description in css in 1px Not a fixed size , Intuitively from what we found on the mobile end 1px The length indicated is small , Therefore, the text display is not clear .
that css Medium 1px What exactly determines the true length of ?
To clarify this concept, we first introduce the concepts of pixels and viewports
1. Pixels
Pixels are the basis of page layout , A pixel represents the smallest area that a computer screen can display , There are two types of pixels :css Pixels and physical pixels .
We are js perhaps css Used in the code px Unit means css Pixels , Physical pixels are also called device pixels , Only related to equipment or hardware , A screen of the same size , The higher the density of the device , The more physical pixels . The following table shows css Specific differences between pixels and physical pixels :
css The pixel is web Provided by developers , stay css An abstract unit of physical pixels used in is only related to the hardware density of the device , The physical pixels of any device are fixed
that css What is the conversion relationship between pixels and physical pixels ? To make it clear css Conversion relationship between pixels and physical pixels , You must first understand what viewports are .
2. viewport
Generalized viewport , Refers to the screen area where the browser displays content , Narrow sense viewports include layout viewports 、 Visual and ideal viewports
(1) Layout the viewport (layout viewport)
Layout viewports define pc The default layout behavior of web pages on the mobile side , Because usually pc High resolution , Layout viewports default to 980px. That is to say, when you do not set up a web page viewport Under the circumstances ,pc The web page at the end will be based on the layout viewport by default , Display on the mobile terminal . So we can clearly see , When the default is layout viewport , Rooted in pc The web page on the mobile terminal is very vague .
(2) Visual viewport (visual viewport)
The visual viewport represents the display area of the web site as seen in the browser , Users can zoom to view the displayed content of the web page , This changes the visual viewport . Definition of visual viewport , It is like holding a magnifying glass to observe the same object from different distances , A visual viewport is just like what appears in a magnifying glass , Therefore, the visual viewport does not affect the width and height of the layout viewport .
(3) Ideal viewport (ideal viewport)
The ideal viewport or should be called “ Ideal layout viewport ”, In mobile devices, it refers to the resolution of the device . let me put it another way , The ideal viewport or resolution is given the physical pixels of the device , The best “ Layout the viewport ”.
In the above viewport , The most important thing is to define the concept of the ideal viewport , In the mobile end , What is the relationship between the ideal viewport or resolution and the physical pixels ?
To clarify the relationship between resolution and physical pixels , Let's introduce a new one with DPR(Device pixel ratio) Device pixel ratio , So we can write this as :
1 DPR = Physical pixel / The resolution of the
Without scaling , One css Pixels correspond to one dpr, in other words , In no zoom
1 CSS Pixels = Physical pixel / The resolution of the
Besides , In the layout of the mobile terminal , We can go through viewport Meta tags to control the layout , For example, in general , We can use the following labels to make the mobile terminal layout in the ideal viewport :
<meta id="viewport" name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1; user-scalable=no;">
Above meta The details of each attribute of the tag are as follows :
Attribute name value description width A positive integer defines the width of the layout viewport , In pixels height A positive integer defines the height of the layout viewport , In pixels , Rarely used initial-scale[0,10] Initial scaling ,1 Means no zoom minimum-scale[0,10] Minimum scale maximum-scale[0,10] Maximum zoom user-scalableyes/no Whether to allow manual scaling of the page , The default value is yes
Among them, let's look at width attribute , When moving the end layout , stay meta In the label, we will width The setting is called device-width,device-width It usually indicates the width of the resolution , adopt width=device-width We set the layout viewport to an ideal viewport .
3. px And adaptive
Above we learned that when we passed viewport Meta tags , When setting the layout viewport to the ideal viewport ,1 individual css Pixels can be expressed as :
1 CSS Pixels = Physical pixel / The resolution of the
We don't know , stay pc The layout viewport at the end is usually 980px, Mobile terminal iphone6 For example , A resolution of 375 * 667, That is, the layout viewport is ideally 375px. For example, now we have a 750px * 1134px The visual draft of , So in pc End , One css Pixels can be calculated as follows :
PC End : 1 CSS Pixels = Physical pixel / The resolution of the = 750 / 980 =0.76 px
And in the iphone6 Next :
iphone6:1 CSS Pixels = Physical pixel / The resolution of the = 750 / 375 = 2 px
That is to say PC End , One CSS Pixels can be 0.76 A physical pixel to represent , and iphone6 in One CSS Pixels represent 2 Individual physical pixels . In addition, different mobile devices have different resolutions , That is to say 1 individual CSS The physical pixels that a pixel can represent are different , So if the css Only through px A unit of length and width , The result is that you can't pass a set of styles , Realize the self adaptation of each end .
Two 、 Media query
We talked about , Under the equipment at different ends , stay css In file ,1px The sizes of the physical pixels represented are different , So through a set of styles , It is impossible to realize self adaptation at each end . From this we associate :
If a set of styles doesn't work , So can you give each device a different set of styles to achieve the adaptive effect ?
The answer is yes .
Use @media Media query can define different styles for different media types , Especially responsive pages , Can be for different screen sizes , Write multiple sets of styles , So as to achieve the adaptive effect . for instance :
@media screen and (max-width: 960px){
body{
background-color:#FF6699
}
}
@media screen and (max-width: 768px){
body{
background-color:#00FF66;
}
}
@media screen and (max-width: 550px){
body{
background-color:#6633FF;
}
}
@media screen and (max-width: 320px){
body{
background-color:#FFFF00;
}
}The above code defines several sets of styles through media query , adopt max-width Sets the maximum resolution at which the style takes effect , The above codes have a resolution of 0~320px,320px~550px,550px~768px as well as 768px~960px Your screen has different background colors .
Search through the media , You can write different styles for different resolution devices to achieve responsive layout , For example, we have different resolution screens , Set up different background pictures . For example, setting up for small screen mobile phones @2x chart , Set up... For large screen phones @3x chart , Through the media query can be very convenient to achieve .
But the disadvantages of media query are also obvious , If the browser size changes , Too many styles need to be changed , So many sets of style code would be tedious .
3、 ... and 、 percentage
In addition to using px Combined with media query to achieve responsive layout , We can also use percentage units " % " To achieve a responsive effect .
For example, when the width or height of the browser changes , Through percentage units , Through percentage units, the width and height of components in the browser can change with the browser , In order to achieve a responsive effect .
To understand the percentage layout , The first thing to understand is :
css Percentage of child elements in (%) Whose percentage is it ?
Intuitive understanding , We might think that the percentage of child elements is completely relative to the direct parent element ,height Percentage relative to height,width Percentage relative to width. Of course, this understanding is correct , But according to css Box model of , except height、width properties , Also has the padding、border、margin And so on. . Then these properties are set to percentages , According to the attributes of the parent element ? Besides, there are border-radius and translate The percentage in the attribute , What is it relative to ? Let's make a concrete analysis .
1. Specific analysis of percentage
(1) Subelement height and width Percent of
The child element height or width Percentage used in , Is the direct parent element relative to the child element ,width Relative to the parent element width,height Relative to the parent element height. such as :
<div class="parent"> <div class="child"></div> </div>
If you set : .father{ width:200px; height:100px; } .child{ width:50%; height:50%; } The display effect is :
(2) top and bottom 、left and right
The child element top and bottom If you set the percentage , In contrast to direct non static location ( Default positioning ) The height of the parent element of , Again
The child element left and right If you set the percentage , In contrast to direct non static location ( Default location ) The width of the parent element .
The display effect is :
(3)padding
The child element padding If you set the percentage , Whether it's vertical or horizontal , All relative to the direct father element width, And with the parent element height irrelevant .
for instance :
.parent{
width:200px;
height:100px;
background:green;
}
.child{
width:0px;
height:0px;
background:blue;
color:white;
padding-top:50%;
padding-left:50%;
}The display effect is :
The initial width and height of the child element is 0, adopt padding You can enlarge the parent element , The blue part of the picture above is a square , And the side length is 100px, explain padding Regardless of width or height , If the percentage is set to be relative to the parent element width.
(4)margin
Follow padding equally ,margin So it is with , The child element margin If set to percentage , Whether it's vertical or horizontal , All relative to the direct parent element width. There are no specific examples here .
(5)border-radius
border-radius Dissimilarity , If you set border-radius As a percentage , It's the width relative to itself , for instance :
<div class="trangle"></div>
Set up border-radius As a percentage :
.trangle{
width:100px;
height:100px;
border-radius:50%;
background:blue;
margin-top:10px;
}The display effect is :
except border-radius Outside , And for example. translate、background-size And so on are relative to their own , Here are not all examples .
2. Percentage unit layout application
Percentage units are still widely used in layout , Here is an application .
For example, we need to implement a rectangle with a fixed aspect ratio , For example, to achieve an aspect ratio of 4:3 The rectangle of , We can use padding Property to implement , because padding Whether it's vertical or horizontal , Percentage units are relative to the width of the parent element , So we can set padding-top As a percentage , Rectangle with adaptive length and width :
<div class="trangle"></div>
Set the style to be adaptive :
.trangle{
height:0;
width:100%;
padding-top:75%;
}By setting padding-top:75%, Of relative specific width 75%, Therefore, a rectangle with a constant ratio of length, width and height is set , The specific effects are shown as follows :
3. Percentage unit defect
From the above introduction to percentage units, we can easily see that if all percentage units are used to realize the responsive layout , There are two obvious disadvantages :
(1) Computational difficulties , If we want to define the width and height of an element , According to the design draft , Must be converted to percentage units . (2) From the section 1 It can be seen that , If percentage is used in each attribute , Attributes relative to the parent element are not unique . such as width and height Relative to the parent element width and height, and margin、padding Both vertical and horizontal directions are relatively wider than the width of the parent element 、border-radius It is relative to the element itself and so on , As a result, our use of percentage units is easy to complicate the layout problem .
Four 、 Adaptive scene rem Solution
1. rem Company
First of all to see , What is? rem Company .rem It's a flexible 、 Scalable units , Convert pixels by browser and display . And em Different units ,rem Units regardless of nesting level , Are only relative to the root element of the browser (HTML Elements ) Of font-size. By default ,html Elemental font-size by 16px, therefore :
1 rem = 12px
For the sake of calculation , Usually you can put html Of font-size Set to :
html{ font-size: 62.5% }In this case :
1 rem = 10px
2. adopt rem To achieve responsive layout
rem Units are all relative to the root element html Of font-size To determine the size of , Root element font-size It is equivalent to providing a benchmark , When the page of size When something changes , It just needs to change font-size Value , So in order to rem The size of an element in a fixed unit will also change in response . therefore , If you pass rem To achieve responsive layout , Just according to the size of the view container , Dynamic change font-size that will do .
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);The above code divides the view container into 10 Share ,font-size Expressed in tenths of the width , Last in header Execute this code in the tag , You can dynamically define font-size Size , thus 1rem Represent different sizes in different visual containers , use rem The fixed unit can realize the adaptive layout of different containers .
3. rem2px and px2rem
If you use... In a responsive layout rem Company , Then there is a problem of unit conversion ,rem2px From rem The conversion px, Don't say that , as long as rem Multiply by the corresponding font-size The size in , It can be converted into px. More applications are px2rem, It means from px Turn into rem.
For example, the given visual draft is 750px( Physical pixel ), If we want to use all the layout units rem To express , A stupid way is to treat all height and width Equal elements , Multiply by the corresponding proportion , Now convert the visual draft into rem Company , Then use one by one rem To express . Another convenient solution is , stay css We still use px To represent the size of an element , Finally, it is finished css After code , take css All of the documents px Company , Turn it into rem Company .
px2rem The principle is very simple , The emphasis is on pretreatment to px Unit css file , After processing, all px become rem Company . This can be achieved in two ways :
1) webpack loader In the form of :
npm install px2rem-loader
stay webpack In the configuration file :
module.exports = {
// ...
module: {
rules: [{
test: /\.css$/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader'
}, {
loader: 'px2rem-loader',
// options here
options: {
remUni: 75,
remPrecision: 8
}
}]
}]
}}
2)webpack Use in postcss plugin
npm install postcss-loader
stay webpack Of plugin in :
var px2rem = require('postcss-px2rem');
module.exports = {
module: {
loaders: [
{
test: /\.css$/,
loader: "style-loader!css-loader!postcss-loader"
}
]
},
postcss: function() {
return [px2rem({remUnit: 75})];
}
}4. rem Example of layout application
The mobile page of Netease News uses rem Layout , Specific examples are as follows :
5. rem Disadvantages of layout
adopt rem Company , You can achieve a responsive layout , In particular, the corresponding postcss Related to the plug-in , The design draft is omitted px To rem The calculation of .rem The company also uses some websites abroad , What I'm talking about here rem To realize the disadvantages of layout , Or the small defect is :
In a responsive layout , Must pass js To dynamically control the root element font-size Size .
in other words css Style and js The code has some coupling . And must change font-size The code for is in css Before the pattern .
5、 ... and . adopt vw/vh To achieve adaptive
1. What is? vw/vh ?
css3 A new unit has been introduced in vw/vh, Related to the view window ,vw Represents the width relative to the view window ,vh Represents the height relative to the view window , except vw and vh Outside , also vmin and vmax Two related units . The specific meaning of each unit is as follows :
Unit meaning vw Relative to the width of the window , The window width is 100vwvh Height relative to the window , The window height is 100vhvminvw and vh The smaller of vmaxvw and vh The greater of
Here we find that the width and height of windows are 100vw/100vh, that vw perhaps vh, The abbreviation vw, It's very similar to the percentage unit .vw and % The difference is :
Unit meaning % Most of them are relative to ancestral elements , There are also situations relative to themselves, such as (border-radius、translate etc. )vw/vh Relative to the size of the window
From the comparison we can see that ,vw Units are similar to percentages , It does make a difference , Previously, we introduced the difficulty of converting percentage units , there vw More like " The ideal percentage unit ". Any level element , In the use of vw In the case of units ,1vw All equal to one percent of the view width .
2. vw Unit conversion
alike , If you want to px The conversion vw Company , It's simple , Just determine the window size of the view ( Layout the viewport ), If we set the layout view to the resolution size , For example, for iphone6/7 375*667 The resolution of the , that px It can be converted into vw:
1px = (1/375)*100 vw
Besides , It can also be done through postcss The corresponding plug-in of , Preprocessing css Make an automatic conversion ,postcss-px-to-viewport Can automatically put px Turn it into vw. postcss-px-to-viewport The default parameter for is :
var defaults = {
viewportWidth: 320,
viewportHeight: 568,
unitPrecision: 5,
viewportUnit: 'vw',
selectorBlackList: [],
minPixelValue: 1,
mediaQuery: false
};By specifying the width and height of the window , And the conversion accuracy , Will be able to px Turn it into vw.
3. vw/vh Unit compatibility
Can be in https://caniuse.com/ Check out the browser versions for vw Unit support .
From the picture above, we find that , Most browsers support vw Company , however ie9-11 I won't support it vmin and vmax, in consideration of vmin and vmax Units are not commonly used ,vw The company has good support in most high-level browsers , however opera The browser as a whole does not support vw Company , If you need compatibility opera Browser layout , It is not recommended to use vw.
Summary : This article introduces the units commonly used in layout , such as px、%、rem and vw wait , And the advantages and disadvantages of different units in the responsive layout .
边栏推荐
- How do individuals register domain names? What are the precautions for individual domain name registration?
- Groovy script engine practice in complex and changeable scenarios
- Tensorflow daily essay (I)
- Tencent cloud harbor private warehouse deployment practice
- EEG microstate as a continuous phenomenon
- How about the XYZ domain name? What are the advantages over other domain names?
- You don't have to spend a penny to build a wechat official website in a minute
- The development and construction of live broadcast app, and the source code of live broadcast app involves all aspects
- Neighbor vote: use proximity voting to optimize monocular 3D target detection (ACM mm2021)
- The basic concept of network is the relationship among services, protocols, processes and ports.
猜你喜欢
随机推荐
How to register the company domain name mailbox? Is the operation process complicated
You don't have to spend a penny to build a wechat official website in a minute
Mysql database backup under Windows Environment
How about the online domain name? Is it easy to use from the current market
Overview of related concepts of social network analysis
Continuously evolving cloud native application delivery
A letter from little potato
Domain name, resolution, SSL certificate product selection
Brief introduction to the working principle of high frequency signal generator
Figure 1 understand Tencent reassurance platform
Oceanus practice - develop MySQL CDC to es SQL jobs from 0 to 1
Build ZABBIX on Tencent ECS
Ups and esxi realize automatic shutdown after power failure
Tomorrow, we will help farmers make their debut together!
How to recover data by splicing database fragments
5 minutes, online from 0 to 1!
PNAs: development of white matter pathways in human brain during the second and third trimester of pregnancy
Network review
TensorFlow 2 quickstart for beginners
Clickhouse alter table execution process



