问题描述
css的1px在PC端就是1px; 在移动端就往往就>1px了
产生原因
- 设备像素比:dpr=window.devicePixelRatio,也就是设备的物理像素与逻辑像素的比值。
- 在
retina屏的手机上,dpr为2或3,css里写的1px宽度映射到物理像素上就有2px或3px宽度。 - 例如:
iPhone6的dpr为2,物理像素是750(x轴),它的逻辑像素为375。也就是说,1个逻辑像素,在x轴和y轴方向,需要2个物理像素来显示,即:dpr=2时,表示1个CSS像素由4个物理像素点组成。
解决方式
实现原理:伪元素 + transform 缩放
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta name="author" content="helang.love@qq.com">
<title>移动端 1px(线条/边框) 解决方案</title>
<style type="text/css">
body{
margin: 0;
padding: 0;
font-size: 14px;
color: #333;
font-family: 'Microsoft YaHei', 'Times New Roman', Times, serif;
}
/* 线条 */
.list{
margin: 0 20px;
list-style: none;
line-height: 42px;
padding: 0;
}
.list>li{
padding: 0;
position: relative;
}
.list>li:not(:first-child):after{ /* CSS匹配非第一个直接子元素 */
content: "";
display: block;
height: 0;
border-top: #999 solid 1px;
width: 100%;
position: absolute;
top: 0;
right: 0;
transform: scaleY(0.5); /* 将 1px 的线条缩小为原来的 50% */
}
/* 边框 */
.button{
line-height: 42px;
text-align: center;
margin: 20px;
background-color: #f8f8f8;
position: relative;
border-radius: 4px;
}
.button:after{
content: "";
position: absolute;
top: -50%;
right: -50%;
bottom: -50%;
left: -50%;
border: 1px solid #999;
transform: scale(0.5);
transform-origin: 50% 50% 0;
box-sizing: border-box;
border-radius: 8px; /* 尺寸缩小 50%,即圆角半径设置为按钮的2倍 */
}
</style>
</head>
<body>
<ul class="list">
<li>线条 1px</li>
</ul>
<div class="button">边框 1px</div>
</body>
</html>
伪元素::after或::before独立于当前元素,可以单独对其缩放而不影响元素本身的缩放