CSS实现1px像素,解决移动端1px线条的显示方式

为什么1px变粗了

相信写移动端的小伙伴会发现移动端css中1px看起来比较粗,这是因为
css里面记录的像素是逻辑像素,而设计师要求的是设备的物理像素。
他们之间存在一个比例关系,可以使用js的window.devicePixelRatio 来获取,也可以使用媒体查询的 -webkit-min-device-pixel-ratio 来获取。当然比例多少与设备相关。在手机上border无法达到我妈想要的效果,这是因为devicePixelRatio 特性导致,IPhone 的 devicePixelRatio == 2,而 border-width: 1px 描述的是设备独立像素,所以 border 被放大到物理像素 2px 显示,在 IPhone 上就显得较粗。
移动端开发常需要在 html 的 header 里添加如下一句:

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

这句话定义了本页面的 viewport 的宽度为设备宽度,初始缩放值和最大缩放值都为 1,并禁止了用户缩放

如和解决

媒体查询

媒体查询利用设备像素比缩放,设置小数像素

.border { border: 1px solid #999 }
@media screen and (-webkit-min-device-pixel-ratio: 2) {
    .border { border: 0.5px solid #999 }
}
@media screen and (-webkit-min-device-pixel-ratio: 3) {
    .border { border: 0.333333px solid #999 }
}

缺点:对设备有要求,兼容差

利用box-shadow 和transfrom

.opeixel {
    position: relative;
    top: 50px;
    width: 300px;
}

.opeixel::after {
    position: absolute;
    bottom: 0;
    left: 0;
    content: '';
    width: 300px;
    box-shadow: 0 0 1px #666;
    transform-origin: 0 bottom;
    transform: scaleY(.5) translateZ(0);
}

/* 设备像素比不小于2 */
@media(min-resolution: 2dppx) {
    .shadow::after {
        box-shadow: 0 0 0 .5px #666;
    }
}

 /* 设备像素比不小于3 */
@media(min-resolution: 3dppx) {
    .shadow::after {
        box-shadow: 0 0 0 0.333333px #666;
    }
}

<span class="opeixel shadow"></span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值