我们知道,在移动端存在物理像素(physical pixel)
和设备独立像素(density-independent pixel)
的概念。物理像素也称为设备像素,它是显示设备中一个最微小的物理部件,每个像素可以根据操作系统设置自己的颜色和亮度。设备独立像素也称为密度无关像素,可以认为是计算机坐标系统中的一个点,这个点代表一个可以由程序使用的虚拟像素(比如CSS像素),然后由相关系统转换为物理像素。根据物理像素和设备独立像素也衍生出了设备像素比(device pixel ratio)
的概念,简称为dpr
,其定义了物理像素和设备独立像素的对应关系,其计算公式为设备像素比 = 物理像素 / 设备独立像素
。因为视网膜(Retina)屏幕的出现,使得一个物理像素并不能和一个设备独立像素完全对等,如下图所示:
dpr
值。为了追求在移动端网页中更好的显示质量,因此我们需要做各种各样的适配处理,最经典的莫过于1px物理像素边框问题,我们需要根据移动端不同的dpr
值来对边框进行处理。在JavaScript中,可以通过window.devicePixelRatio
来获取当前设备的dpr
,在CSS中,可以通过-webkit-device-pixel-ratio,-webkit-min-device-pixel-ratio和-webkit-max-device-pixel-ratio
来进行媒体查询,从而针对不同的设备,来做一些样式适配。这里对于1px像素的边框问题,给出一种最常见的写法:.border-1px { position: relative; } .border-1px::after { content: ""; position: absolute; left: 0; bottom: 0; 100%; height: 1px; background-color: #000; -webkit-transform: scaleY(.5); transform: scaleY(.5); } @media only screen and (-webkit-min-device-pixel-ratio: 2.0), (min-device-pixel-ratio: 2.0) { .border-1px::after { -webkit-transform: scaleY(.5); transform: scaleY(.5); } } @media only screen and (-webkit-min-device-pixel-ratio: 3.0), (min-device-pixel-ratio: 3.0) { .border-1px::after { -webkit-transform: scaleY(.33); transform: scaleY(.33); } }