移动端border:1px问题解决方案
其实移动端使用rem中有两个地方无法使用rem单位,第一个就是字体大小使用rem的方式无法保证在不同分辨率的手机下,显示合适的字体大小,所以使用px单位和媒介查询的方式,字体大小的变化范围不会太大,甚至不变也能接受。第二点就是border其实我们并不想要border根据不同分辨率去变化,任何分辨率下都设置1px,但是可能dpr的原因显示上的感受可能又会变成2px、3px等,所以使用如下方式
了解设备像素和css像素的因该知道,通常我们在写移动端时,是按照设计稿标注的像素除以设备的DPR来写真实的像素,
比如在iPhone6上,我们写的20px字体世界上在视觉效应上有20px;
所以当我们写1px边框时,在手机上看起来会变粗变为2px;
对此有如下解决方案:
.border-1px(@color){
position:relative;
&::after{
display: block;
position: absolute;
left:0;
bottom:0;
border-top:1px solid @color;
width:100%;
content:' ';
}
}
@media (-webkit-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5) {
.border-1px{
&::after{
-webkit-transform: scaleY(0.7);
transform: scaleY(0.7);
}
}
}
@media (-webkit-device-pixel-ratio: 2),(min-device-pixel-ratio: 2) {
.border-1px{
&::after{
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
}
}
}
@media (-webkit-device-pixel-ratio: 3),(min-device-pixel-ratio: 3) {
.border-1px{
&::after{
-webkit-transform: scaleY(0.33);
transform: scaleY(0.33);
}
}
}
当然这里使用了less,现在开发移动端基本也是框架开发,uniapp就不说了,如果使用vue等框架,呢么 这不失为一种合适的方案。1*2*0.5 === 1px 1*1.5*0.7==1 1*3*0.333==1
对了上面是单边的还有四条边的情况(更推荐下面的写法,当然如果1px 2px 3px无所谓的话 就直接不管也行):
//单条border
.border-1px{
position: relative;
&:after{
content: '';
display: block;
position: absolute;
width: 100%;
left: 0;
bottom: 0;
height: 1px;
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
}
}
//四条border
.border-1px{
position: relative;
&:after{
content: '';
position: absolute;
top: 0;
left: 0;
border: 1px solid #fff;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 200%;
height: 200%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
//-webkit-transform-origin: left top;
//transform-origin: left top;
}
}