随着移动端的web项目愈来愈多,设计师的要求也愈来愈高。在移动端上经过1px实现一条1像素的线时,它并非真正的1像素,比真正的1像素要粗一点。
那么为何会产生这个问题呢?主要是跟一个东西有关,DPR(devicePixelRatio) 设备像素比,它是默认缩放为100%的状况下,设备像素和CSS像素的比值。css
window.devicePixelRatio=物理像素 /CSS像素
复制代码
目前主流的屏幕DPR=2 (iPhone 8),或者3 (iPhone 8 Plus)。拿2倍屏来讲,设备的物理像素要实现1像素,而DPR=2,因此css 像素只能是 0.5。
通常设计稿是按照750来设计的,它上面的1px是以750来参照的,而咱们写css样式是以设备375为参照的,因此咱们应该写的0.5px就行了啊! 试过了就知道,iOS 8+系统支持,安卓系统不支持。html
.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 }
}
复制代码
<span class="border-1px">1像素边框问题</span>
// less
.border-1px{
position: relative;
&::before{
content: "";
position: absolute;
left: 0;
top: 0;
width: 200%;
border:1px solid red;
color: red;
height: 200%;
-webkit-transform-origin: left top;
transform-origin: left top;
-webkit-transform: scale(0.5);
transform: scale(0.5);
pointer-events: none; /* 防止点击触发 */
box-sizing: border-box;
@media screen and (min-device-pixel-ratio:3),(-webkit-min-device-pixel-ratio:3){
width: 300%;
height: 300%;
-webkit-transform: scale(0.33);
transform: scale(0.33);
}
}
}
复制代码
注意:空元素(不能包含内容的元素)不支持 ::before,::afterweb
<span class="border-1px">1像素边框问题</span>
.border-1px{
box-shadow: 0px 0px 1px 0px red inset;
}
复制代码
弄出1px像素边框的实质是弄出0.5px这样的边框,因此咱们能够利用相似于这样的图片,使得“border-image-slice”为2,那么实际上边框有一半是透明的,便可获得咱们想要的“1px边框” bash
<div class="test">1像素边框</div>
.test{
border: 1px solid transparent;
border-image: url('./border-1px.png') 2 repeat;
}
复制代码
根据设备像素设置viewport,代码只须要写正常像素就能够了。less
<html>
<head>
<title>1px question</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta name="viewport" id="WebViewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<style>
html {
font-size: 1px;
}
* {
padding: 0;
margin: 0;
}
.top_b {
border-bottom: 1px solid #E5E5E5;
}
.a,.b {
box-sizing: border-box;
margin-top: 1rem;
padding: 1rem;
font-size: 1.4rem;
}
.a {
width: 100%;
}
.b {
background: #f5f5f5;
width: 100%;
}
</style>
<script>
var viewport = document.querySelector("meta[name=viewport]");
//下面是根据设备像素设置viewport
if (window.devicePixelRatio == 1) {
viewport.setAttribute('content', 'width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no');
}
if (window.devicePixelRatio == 2) {
viewport.setAttribute('content', 'width=device-width,initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no');
}
if (window.devicePixelRatio == 3) {
viewport.setAttribute('content', 'width=device-width,initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no');
}
var docEl = document.documentElement;
var fontsize = 32* (docEl.clientWidth / 750) + 'px';
docEl.style.fontSize = fontsize;
</script>
</head>
<body>
<div class="top_b a">下面的底边宽度是虚拟1像素的</div>
<div class="b">上面的边框宽度是虚拟1像素的</div>
</body>
</html>
复制代码