移动端1px边框解决方案

在 retina 屏中,设备像素比为 2(iPhone6/7/8) 或 3(iPhone6Plus/7Plus/8Plus),1px 的边框看起来比真的 1px 更宽。

1. 使用伪类加transform的方式

元素本身不定义边框,伪元素定义 1px 边框,并且根据根据设备像素比值设置缩放比例,设备像素比为 3 时设置为 0.33,设备像素比为 2 时设置 0.5。

2. 当直接设置边框 1px 时:

<div class="border-1px"></div>
.border-1px {
	border-top: 1px solid #666;
}

直接设置1px边框,在 iPhone6Plus/7Plus/8Plus 和 iPhone6/7/8 模拟机上测试效果:

移动端1px边框问题-直接设置1px

3. 设置一条边的情况

<div class="border-1px"></div>
.border-1px {
	position: relative;
}

.border-1px:after {
	position: absolute;
	content: "";
	top: -50%;
	bottom: -50%;
	left: -50%;
	right: -50%;
	-webkit-transform: scale(0.5);
	transform: scale(0.5);
	border-top: 1px solid #666;			
	/* 下面兼容非 retina 屏,原尺寸,不放大缩小 */
	transform: scaleY(1);
	box-shadow: 0 0 0 1px #000;
}

@media only screen and (-webkit-min-device-pixel-ratio: 3) {
	border-1px::after {
		-webkit-transform: scaleY(0.33333333);
		transform: scaleY(0.33333333);
	}
}

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
	border-1px::after {
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
	}
}

设置一条窄边框在 iPhone6Plus/7Plus/8Plus 模拟机上测试效果:

移动端1px边框问题-使用伪元素和缩放方式设置1条边

设置一条窄边框在 iPhone6/7/8 模拟机上测试效果:

移动端1px边框问题-使用伪元素和缩放方式设置1条边

4. 设置四条边的情况

四条边的情况设置 CSS:

.border-1px {
	position: relative;
	height: 48px;
	border-radius: 8px;
}
.border-1px::after {
	content: '';
	position: absolute;
	top: 0;
	left: 0;
	box-sizing: border-box;
	transform-origin: left top;
    /* 下面兼容非 retina 屏,原尺寸,不放大缩小 */
	width: 100%;
	height: 100%;
	transform: scale(1);
	box-shadow: 0 0 0 1px #000;
	border-radius: 8px;
}

@media only screen and (-webkit-min-device-pixel-ratio: 2) {
	.border-1px::after {
		width: 200%; /* 这里放大 2 倍 */
		height: 200%; /* 这里放大 2 倍 */
		transform: scale(0.5); /* 这里缩小为 1/2 */
		box-shadow: 0 0 0 0.5px #000; /* 这里缩小为 1/2 */
		border-radius: 16px; /* 这里放大 2 倍 */
	}
}

@media only screen and (-webkit-min-device-pixel-ratio: 3) {
	.border-1px::after {
		width: 300%; /* 这里放大 3 倍 */
		height: 300%; /* 这里放大 3 倍 */
		transform: scale(0.33333333); /* 这里缩小为 1/3 */
		box-shadow: 0 0 0 0.33333333px #000; /* 这里缩小为 1/3 */
		border-radius: 24px; /* 这里放大 3 倍 */
	}
}

设置四条窄边框在 iPhone6Plus/7Plus/8Plus 模拟机上测试效果:

移动端1px边框问题-使用伪元素和缩放方式设置4条边

设置四条窄边框在 iPhone6/7/8 模拟机上测试效果:

移动端1px边框问题-使用伪元素和缩放方式设置4条边

posted @ 2019-07-25 22:56  艾前端  阅读(2238)  评论(0编辑  收藏  举报