移動端1px產生原因及解決之道
阿新 • • 發佈:2018-12-23
產生原因
因為Retine屏的解析度始終是普通螢幕的2倍,1px的邊框在devicePixelRatio=2的retina屏下會顯示成2px,所以在高清瓶下看著1px總是感覺變胖了,關於詳細原因介紹參考大漠的文章:http://www.w3cplus.com/css/towards-retina-web.html
解決之道
1.在ios8+中當devicePixelRatio=2的時候使用0.5px
div{
border:1px solid #000;
}
@media (-webkit-min-device-pixel-ratio: 2) {
div{
border :0.5px solid #000;
}
}
2. transform: scale(0.5)
//下面是通過偽類實現的1px線條
.onePxHei(@borColor:#efefef,@borPx:1px){
&:after{
position: absolute;
bottom: -1px;
left: 0;
width: 100%;
height: 2px;
-webkit-transform: scale(1,.5);
transform: scale(1,.5);
-webkit-transform-origin : 0 0;
transform-origin: 0 0;
content: '';
background-color: @borColor;
}
}
本人用的是less,這是mixin
缺點:圓角無法實現,實現4條邊框比較麻煩
3.使用background-image
//通過background實現的1px,設定到dom本身,不會繪製padding和margin區域
.onePxBottomByBg(@borColor:#efefef,@borPx:1px){
background-image: -webkit-linear-gradient(top, @borColor , @borColor 50%, transparent 50%);
background-image: linear-gradient(180deg, @borColor, @borColor 50%, transparent 50%);
background-size: 120% @borPx;
background-repeat: no-repeat;
background-position: bottom left;
background-origin: content-box;
}
優點:基本所有場景都能滿足,包含圓角的button,單條,多條線
缺點:大量使用漸變可能導致效能瓶頸
總結:建議background-image+transform: scale(0.5)配合使用,優先使用縮放