rem是一个单位,相对于html的fontsize而言。经常用来适配移动端页面
逻辑像素:软件所能达到的分辨率,我们开发实际使用的分辨率,eg:320X568
物理像素(设备像素):设备实际的像素,就是我们平时买手机说的分辨率,是设计人员使用的分辨率,eg:640X1136
逻辑像素和物理像素之间存在一个缩放因子,有兴趣的可以去看看retina屏。
虽然移动端和pc端都是单位都是px,但是这两个px却是不同的,前者是逻辑像素,后者是物理像素。
设备 苹果手机 | 宽 宽度 | 高 高度 | 对角线 对角线 | 逻辑分辨率(点) | 比例因子 | 设备分辨率(像素) | PPI |
3GS | 2.4英寸(62.1毫米) | 4.5英寸(115.5毫米) | 3.5英寸
| 小320x480 | @ 1X | 小320x480 | 163 |
4(S) | 2.31英寸(58.6毫米) | 4.5英寸(115.2毫米) | 3.5英寸 | 小320x480 | @ 2倍 | 640×960 | 326 |
5C | 2.33英寸(59.2毫米) | 4.90英寸(124.4毫米) | 4英寸 | 320x568 | @ 2倍 | 640x1136 | 326 |
5(S) | 2.31英寸(58.6毫米) | 4.87英寸(123.8毫米) | 4英寸 | 320x568 | @ 2倍 | 640x1136 | 326 |
6 | 2.64英寸(67.1毫米) | 5.44英寸(138.3毫米) | 4.7英寸 | 375x667 | @ 2倍 | 750x1334 | 326 |
6+ | 3.07英寸(77.9毫米) | 6.23英寸(158.2毫米) | 5.5英寸 | 414x736 | @ 3倍 | (1242x2208 - >) 1080×1920 | 401 |
我们现在一般设计图一般基于iphone的,一般是640或750,fonsize是40px。
要使用rem,可以分为两步
1). 计算出html的fontsize:(按640设计稿)------- 这段代码应该放在body之前,因为应该在渲染页面之前就计算好,避免出现闪烁问题。
<script>
function adjustFontsize() {
var docEle = document.documentElement;
var width = (screen.width > 0) ? (window.innerWidth >= screen.width || window.innerWidth == 0) ? screen.width :
window.innerWidth : window.innerWidth;
if (width) {
width = Math.min(width, 750);
docEle.style.fontSize = 20 * (width / 375) + 'px';
}
}
var evt = 'onorientationchange' in window ? 'orientationchange' : 'resize';
window.addEventListener(evt, adjustFontsize, false);
adjustFontsize();
</script>
2). px转换为rem
可以使用sublime的插件cssrem,调整下fontsize
可以使用scss的函数功能实现
@function rem($target, $context: 40px) {
@return ($target / $context) * 1rem;
}
使用的时候
padding: rem(10px) 0;