什么是rem布局
简单来说,使用rem布局,在设置字体,宽高等大小时,是由html根元素的font-size决定的,并不一定是真实的font-size大小;
- px实现rem布局;
例:当html的font-size为100px时,此时0.2rem == 20px;
<style>
html {
font-size: 100px;
}
.p1 {
font-size: .2rem;
}
.p2 {
font-size: 20px;
}
</style>
<body>
<p class="p1">我是rem布局</p>
<p class="p2">我是rem布局</p>
</body>
当html的font-size为50px时,0.2rem == 10px;
html {
font-size: 50px;
}
.p1 {
font-size: .2rem;
}
.p2 {
font-size: 10px;
}
同理,当html的font-size为200px时, 0.2rem == 40px;
所以说,rem布局是由根元素的font-size决定的,设置html的font-size(px),可以实现一些需求,比如“大中小”字体的切换,只需改变html的font-size即可;但同时会存在一些问题:
<style>
html {
font-size: 100px;
}
.p1 {
font-size: .2rem;
}
</style>
<body>
<p class="p1">我是rem布局我是rem布局我是rem布局</p>
</body>
上面的布局,在不同的手机屏幕尺寸下,有的一行可以展示,有的却会换行,这就有可能导致布局上出现问题;
- vw实现rem布局
屏幕的宽度 = 100vw ;
vw的计算方式 100 / (UI图纸的宽度 / 100);
例
<style>
/* 假设UI图宽668px vw = 100 / (668 / 100) ≈ 14.97 */
html {
font-size: 14.97vw;
}
.p1 {
font-size: .2rem;
}
.p2 {
font-size: 20px;
}
</style>
<body>
<p class="p1">我是rem布局</p>
<p class="p2">我是rem布局</p>
</body>
此时的0.2rem != 20px, 0.2rem只是相当于 20px在真实的667px中占的比例(比如,667px宽可以放32个20px的字,那么任意一个屏幕,都可以放32个0.2rem的字)
<style>
/* 假设UI图宽668px vw = 100 / (668 / 100) ≈ 14.97 */
body {
margin: 0;
padding: 0;
}
html {
font-size: 14.97vw;
}
.p1 {
font-size: .2rem;
}
.p2 {
font-size: 20px;
}
</style>
<body>
<p class="p1">一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二</p>
<p class="p2">一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二</p>
</body>
所以vw不用担心布局乱掉的问题;
在实际开发中,可根据实际需求,选择不同的实现方式;