foreword
Hello everyone, I'm Lin Sanxin, uses the most simple and easy-to-understand words to describe the most difficult knowledge points is my motto, foundation is the premise of advanced is my original intention
REM layout
REM
is a unit, REM layout is a layout based on
REM
.
REM
in R
is Root
mean, it represents root tag, so that
REM
the size of the unit is based root tag of
font-size
to decide, but root tag is
html
If html
of font-size: 14px
, then 1rem = 20px
of the whole page, if html
of 1rem = 14px
, then font-size: 20px
of the whole page
design draft
Then if I give you a design draft now, the width is 800px
, and there is a button in the design draft whose length and width are 100px、20px
, then when you draw this button on the web page, what should the length and width be rem
?
Web page
The design draft is a design draft, and the web page is a web page. The width of the design draft is fixed, but the width of the web page is not fixed, because the screen sizes of different computers are different. Here we first select a web page of 1920px
example
We can regard 1px
on the design draft as 1rem
, then 1920px
on the webpage of 1rem
is (1920 / 800 * 1)px
The button is 100px=100rem
on the design draft, and the button on the webpage is also 100rem
, but the size of the two rems is different~~
practice
We prepare three files index.html、index.css、index.js
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="stylesheet" href="./index.css" /> </head> <body> <button class="btn">按钮</button> </body> <script src="./index.js"></script> </html>
index.css
html { font-size: 1px; } .btn { width: 100rem; height: 20rem; }
index.js
// multiple是倍数,默认是1,也可以自定义 const computedFontStyle = ( clientWidth, designWidth, multiple = 1) => { return clientWidth / designWidth * multiple } // 每次屏幕宽度改变时,改变html标签的font-size window.onresize = () => { // 获取html对象 const docEl = document.documentElement // 获取网页宽度 const clientWidth = docEl.clientWidth // 计算html的font-size const rootFontStyle = computedFontStyle(clientWidth, 800) docEl.setAttribute('style', `font-size: ${rootFontStyle}px`) }
When we change the screen width, the font-size
of the html will change in real time to achieve the effect of changing the size of rem
, and at the same time change the corresponding height and width of the button
Epilogue
I'm Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends and fish together haha, touch the fish group, add me, please note [Si No]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。