移动端 1px 如何适配?

·  阅读 54

要解决移动端 1px 问题,本质就是让高清屏用一个物理像素去展示一个css像素

解决方法:用伪类元素与 transform 缩放

四边框的情况:

  • index.html
<!DOCTYPE html>
<html lang="en">
<head> 
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="./index.css" />  
</head> 
<body> 
    <div class="retina-border">retina border 演示</div>
    <br />   
    <div class="normal-border">normal border 演示</div> 
</body>
</html>
复制代码
  • index.css
/* 解决 1px 的代码 */
.retina-border {
    position: relative;
}
.retina-border::before {
    content: '';  
    position: absolute;
    width: 100%;
    height: 100%; 
    transform-origin: left top;
    box-sizing: border-box;
    pointer-events: none; 
    border-width: 1px;
    border-style: solid;
    border-color: red;
}
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) {  .retina-border::before {   
    width: 200%; 
    height: 200%; 
    transform: scale(0.5); 
    }
}
@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx) {  .retina-border::before {  
    width: 300%; 
    height: 300%;   
    transform: scale(0.33);
    }
}

/* 一般情况下默认边框 */
.normal-border { 
    border: 1px solid red;
}
复制代码

上边框/下边框的情况:

.retina-border {
    position: relative;
}
.retina-border::before {
	content: "";
	width: 100%;
	position: absolute;
	top: 0;  /* 下边框 bottom: 0; */
	border-bottom: 1px solid red;
	-webkit-transform: scaleY(0.5);
	transform: scaleY(0.5);
}
复制代码

左边框/右边框的情况:

.retina-border {
    position: relative;
}
.retina-border::before {
	content: "";
	height: 100%;
	position: absolute;
	left: 0;  /* 右边框 right: 0; */
	border-left: 1px solid red;
	-webkit-transform: scaleY(0.5);
	transform: scaleY(0.5);
}
复制代码
分类:
前端
标签:
分类:
前端
标签: