程序员web 前端Css

移动端1px像素问题

2019-03-25  本文已影响247人  乔儿q

一、问题

写css的样式时候,设置元素的边框为1px, 但在移动端上看起来却像是2px

二、为什么会有1px问题?

1.要处理这个问题,得先知道设备的物理像素(设备像素)逻辑像素(css像素)

物理像素:

移动设备出厂时,不同设备自带的不同像素

逻辑像素:

css中记录的像素

UI设计师要求的1px是指设备的物理像素1px,而CSS里记录的像素是逻辑像素,它们之间存在一个比例关系:设备像素比dpr(devicePixelRatio) = 设备像素 / CSS像素
dpr通常可以用 javascript 中的 window.devicePixelRatio 来获取,也可以用媒体查询的 -webkit-min-device-pixel-ratio 来获取。当然,比例多少与设备相关。
在手机上border无法达到我们想要的效果。这是因为 devicePixelRatio 特性导致,iPhone的 devicePixelRatio==2,而 border-width: 1px; 描述的是设备独立像素,所以,border被放大到物理像素2px显示,在iPhone上就显得较粗。

三、解决方案

利用选择器:before或:after和transfrom

原理:

把原先元素的border去掉,用:before或:after重做border,并用transfrom中的scale缩小一半,原先的元素相对定位,新做的border绝对定位

<style>
//单条border样式设置:
.box{
  border:none; 
  position: relative;
}
.box:bofore{   
     content: '';
     position: absolute; 
     bottom: 0; 
     background: #000; 
     width: 100%; 
     height: 1px;
     transform: scaleY(0.5); 
     transform-origin: 0 0;     
}

//四条border样式设置:
    .box{
        border:none;
         position: relative;
     }
    .box:before{
        content: '';
        width: 1200px;
        height: 1200px;
        border: 1px solid red;
        transform: scale(0.5);
        position: absolute;
        top: 0;
        left: 0;
        transform-origin: top left;
    }
</style> 
<body>
    <div class="box">box-shadow-1px</div>
</body>
<script>
    //结合js来代码来判断是否是Retina屏

  
    if(window.devicePixelRatio && devicePixelRatio >= 2){
         document.querySelector('div').className = 'box';
    }
</script>




上一篇 下一篇

猜你喜欢

热点阅读