由於分辨率 DPI 的差異,高清手機屏上的 1px 實際上是由 2×2 個像素點來渲染,有的屏幕甚至用到了 3×3 個像素點
所以 border: 1px 在移動端會渲染為 2px 的邊框
雖然用戶在實際使用的時候,很難發現這 1px 的差異,但是設計師往往會在這 1px 上較勁,這就產生了經典的 “一像素問題”
最簡單的解決辦法,就是用圖片做邊框,只是修改顏色不太方便。除此之外,還有兩種常用的辦法
一、transform:scale
使用偽類 :after 或者 :before 創建 1px 的邊框,然后通過 media 適配不同的設備像素比,然后調整縮放比例,從而實現一像素邊框
首先用偽類創建邊框
.border-bottom{ position: relative; border-top: none !important; } .border-bottom::after { content: " "; position: absolute; left: 0; bottom: 0; width: 100%; height: 1px; background-color: #e4e4e4; -webkit-transform-origin: left bottom; transform-origin: left bottom; }
然后通過媒體查詢來適配
/* 2倍屏 */ @media only screen and (-webkit-min-device-pixel-ratio: 2.0) { .border-bottom::after { -webkit-transform: scaleY(0.5); transform: scaleY(0.5); } } /* 3倍屏 */ @media only screen and (-webkit-min-device-pixel-ratio: 3.0) { .border-bottom::after { -webkit-transform: scaleY(0.33); transform: scaleY(0.33); } }
這種辦法的邊框並不是真正的 border,而是高度或者寬度為 1px 的塊狀模型,所以這種辦法不能做出圓角,一般都用來畫分割線
二、viewport
網頁的內容都渲染在 viewport 上,所以設備像素比的差異,直接影響的也是 viewport 的大小
通過 js 獲取到設備像素比,然后動態添加 <meta> 標簽
<script type="text/javascript"> (function() { var scale = 1.0;
if (window.devicePixelRatio === 2) { scale *= 0.5; } if (window.devicePixelRatio === 3) { scale *= 0.333333; } var text = '<meta name="viewport" content="initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ', width=device-width, user-scalable=no" />'; document.write(text); })(); </script>