解決CSS移動端1px邊框問題

移動項目開發中,安卓或者IOS等高分辨率屏幕會把1px的border渲染成2px來顯示,網上搜了一下,解決方法以下:css

1、利用css中的transform的縮放屬性解決,推薦這個。以下面代碼。

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>解決1px邊框問題</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"/>
    <style>
        .line {position:relative;}
        .line:after {width:200%;height:200%;position:absolute;top:0;left:0;z-index:0;content:"";-webkit-transform:scale(0.5);-webkit-transform-origin:0 0;transform:scale(0.5);transform-origin:0 0;}

        .list {width:100%;margin:auto;list-style:none;padding:0;}
        .list:after {border:1px solid #ccc;border-radius:10px;}
        .item {padding:10px;}
        .item:after {border-bottom:1px solid #ccc;}
        .item:last-child:after {display:none;}
    </style>
</head>
<body>


<ul class="list line">
    <li class="item line">item001</li>
    <li class="item line">item002</li>
    <li class="item line">item003</li>
    <li class="item line">item004</li>
    <li class="item line">item005</li>
    <li class="item line">item006</li>
    <li class="item line">item007</li>
    <li class="item line">item008</li>
    <li class="item line">item009</li>
    <li class="item line">item010</li>
</ul>


</body>
</html>

這個主要利用after僞類進行縮放。調用公共class,仍是很方便的。html

 

2、JS判斷是否支持0.5px邊框,是的話,則輸出類名hairlines  

if (window.devicePixelRatio && devicePixelRatio >= 2) {
  var testElem = document.createElement('div');
  testElem.style.border = '.5px solid transparent';
  document.body.appendChild(testElem);
  if (testElem.offsetHeight == 1)
  {
    document.querySelector('html').classList.add('hairlines');
  }
  document.body.removeChild(testElem);
}

.hairlines .box {}web

目前在用這個方法,使用很方便,無須多餘的class,惋惜支持的不是很好,IOS8+以上才能夠。app

 

3、box-shadow 陰影

-webkit-box-shadow:0 1px 1px -1px rgba(0, 0, 0, 0.5);

最早用的就是這個方法,IOS沒問題。不少安卓機顯示就是坨翔,黑乎乎的描邊。。url

 

4、background-image

.border {
  background-image:linear-gradient(180deg, red, red 50%, transparent 50%),
  linear-gradient(270deg, red, red 50%, transparent 50%),
  linear-gradient(0deg, red, red 50%, transparent 50%),
  linear-gradient(90deg, red, red 50%, transparent 50%);
  background-size: 100% 1px,1px 100% ,100% 1px, 1px 100%;
  background-repeat: no-repeat;
  background-position: top, right top,  bottom, left top;
  padding: 10px;
    }

也能實現效果,使用很不方便spa

 

5、圖片

.border-image{
    border-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAECAYAAABP2FU6AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAB5JREFUeNpiPnH8zH/G////MzAxAAHTyRNn/wMEGABpvQm9g9TJ1QAAAABJRU5ErkJggg==") 2 0 stretch;
border-width: 0px 0px 1px;
}

顯示效果有點模糊,並且萬一之後要修改個顏色,那不坑爹了。scala

 

因此,目前推薦第一種方法。code

相關文章
相關標籤/搜索