前言
最近在写移动端 H5 应用,遇到一个值得记录下来的点。现在从它的由来到实现,我们来聊一下移动端 1px,说 1px 不够准确,应该说成 1 物理像素。
通过阅读下面文章,你将会理解以下问题:
问题
- 为什么有 1px 这个问题?
- 实现 1px 有哪些方法?这些方法分别有哪些优缺点?
- 开源项目中使用的哪些解决方案?
- 如何在项目中处理 1px 的相关问题?
由来
基本概念
首先,我们要了解两个概念,一个是像素(pixel)可以简写为px,另外一个是设备像素比(DPR)
像素 :指在由一个数字序列表示的图像中的一个最小单元,单位是 px,不可再次分割了。
设备像素比(DPR): 设备像素比 = 设备像素 / 设备独立像素。
下面我来简单解释下几个概念
- CSS 像素 (虚拟像素):指的是 CSS 样式代码中使用的逻辑像素,在 CSS 规范中,长度单位可以分为两类,绝对单位以及相对单位。px 是一个相对单位,相对的是设备像素。
- 设备像素 (物理像素):指设备能控制显示的最小物理单位,意指显示器上一个个的点。从屏幕在工厂生产出的那天起,它上面设备像素点就固定不变了,和屏幕尺寸大小有关。
- 设备独立像素 (逻辑像素):可以认为是计算机坐标系统中得一个点,这个点代表一个可以由程序使用的虚拟像素(比如: CSS 像素),这个点是没有固定大小的,越小越清晰,然后由相关系统转换为物理像素。
也就是说,当逻辑像素是 1pt 时,在 DPR 为 2 的 设备上显示为 2px 的物理像素
实践
归根结底有两种方案,一种是利用 css 中的transfrom:scaleY(0.5)
,另一种是设置 媒体查询根据不同 DPR 缩放
解决方案一
原理
利用 css 的 伪元素::after
+ transfrom
进行缩放
为什么用伪元素? 因为伪元素::after
或::before
是独立于当前元素,可以单独对其缩放而不影响元素本身的缩放
伪元素大多数浏览器默认单引号也可以使用,和伪类一样形式,而且单引号兼容性(ie)更好些
实现
<div class="cell border-1px"> cell <div>
<style>
.cell {
width: 100px;
height: 100px;
}
<!--全部边框-->
.border-1px:after {
content: '';
position: absolute;
box-sizing: border-box;
top: 0;
left: 0;
width: 200%;
height: 200%;
border: 1px solid #000;
border-radius: 4px;
-webkit-transform: scale(0.5);
transform: scale(0.5);
-webkit-transform-origin: top left;
}
<!--单边框,以上边框为例-->
.border-1px-top:before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
border-top: 1px solid red;
transform: scaleY(.5);
transform-origin: left top;
}
</style>
解决方案二(升级方案一)
原理
使用 less 对公共代码(方案一)封装,同时增加媒体查询分别对不同 DPR 的设备,进行不同的缩放
.border(
@borderWidth: 1px;
@borderStyle: solid;
@borderColor: @lignt-gray-color;
@borderRadius: 0) {
position: relative;
&:before {
content: '';
position: absolute;
width: 98%;
height: 98%;
top: 0;
left: 0;
transform-origin: left top;
-webkit-transform-origin: left top;
box-sizing: border-box;
pointer-events: none;
}
@media (-webkit-min-device-pixel-ratio: 2) {
&:before {
width: 200%;
height: 200%;
-webkit-transform: scale(.5);
}
}
@media (-webkit-min-device-pixel-ratio: 2.5) {
&:before {
width: 250%;
height: 250%;
-webkit-transform: scale(.4);
}
}
@media (-webkit-min-device-pixel-ratio: 2.75) {
&:before {
width: 275%;
height: 275%;
-webkit-transform: scale(1 / 2.75);
}
}
@media (-webkit-min-device-pixel-ratio: 3) {
&:before {
width: 300%;
height: 300%;
transform: scale(1 / 3);
-webkit-transform: scale(1 / 3);
}
}
.border-radius(@borderRadius);
&:before {
border-width: @borderWidth;
border-style: @borderStyle;
border-color: @borderColor;
}
}
.border-all(
@borderWidth: 1px;
@borderStyle: solid;
@borderColor: @lignt-gray-color;
@borderRadius: 0) {
.border(@borderWidth; @borderStyle; @borderColor; @borderRadius);
}