前言
移动端1像素线之所以是个问题,是因为移动端有像素比的概念。
什么是像素比(devicePixelRatio)呢?
像素比 = 物理像素/设备独立像素
其中,物理像素是指设备屏幕所拥有的实际像素点,其值是固定的,在设备出厂时就设置好了的。设备独立像素,顾名思义就是独立于设备的用于逻辑上衡量像素的单位,又称为逻辑像素。
在开发时,你会发现用样式写了1px线后,在移动端设备上看起来会变粗,这就是因为像素比大于1,导致在移动端实际展示的线是大于1px的。
实现
目前移动端1px线变粗的解决方法,有以下几种:
- 使用1px线的图片,缺点在于,需要设计师做图,圆角可能会出现模糊
- 利用 box-shadow,优点是没有圆角问题,缺点是颜色不好控制
- 使用伪元素+transform: scale(0.5) ,没有圆角问题,颜色可控,总体比较灵活
以下介绍伪元素+transform的具体实现:
HTML:
<div class="test"> 1px line test</div>
CSS:
.test{
position: relative;
color: red;
height: 50px;
width: 200px;
background-color: bisque;
}
test:before{
content: '';
position: absolute;
width: 100%;
height: 1px;
background: #ee0707;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2) {
.test:before{
transform: scaleY(0.5);
transform-origin: left top;
}
}
使用媒体查询来判断当下像素比是否为2,是的话,再对1px进行缩放。否则,无脑缩放0.5倍的话,在pc端某些浏览器会出现1px线神奇消失的问题。
兼容
如果考虑兼容浏览器的话,上面的css可以优化如下:
@media only screen and (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2) {
.test:before{
-webkit-transform: scaleY(0.5);
-moz-transform: scaleY(0.5);
-o-transform: scaleY(0.5);
-ms-transform: scaleY(0.5);
transform: scaleY(0.5);
-webkit-transform-origin: left top;
-moz-transform-origin: left top;
-o-transform-origin: left top;
-ms-transform-origin: left top;
transform-origin: left top;
}
}
如果需要竖线的话,可以在scale前添加rotate属性实现,但注意是在scale之前添加,因为这两个属性都会对坐标轴本身产生影响,需要根据具体需求具体分析。