这边文章用来记录Web(包括PC和移动端)开发过程中遇到的一些疑难问题的解决方案。
P1、 '1像素边框'问题
在平时的开发过程中,经常会遇到UI给的设计稿中元素的边框为0.5px
,这里的0.5px
指的是CSS像素,对于设备像素比为2的屏幕来说,对应的物理像素就是1个像素,也就是说设计稿的本意是让我们实现真实的占据1个物理像素点的边框。由于直接设置对应CSS属性为0.5px
在各平台和浏览器中兼容性很不好,网上给出了很多解决方案,这里仅列出最常用的被论证有效的解决方案。
1.根据设备像素比transform
缩放,常借助伪元素
div {
position: relative;
}
div::after {
content: '';
position: absolute;
z-index: 999;
top: 0;
left: 0;
border: 1px solid red;
transform-origin: 0 0;
}
@media (-webkit-min-device-pixel-ratio:2),(min-device-pixel-ratio:2){
div::after{
width: 200%;
height: 200%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
/*border-radius: $radius * 2;有圆角*/
}
}
@media (-webkit-min-device-pixel-ratio:2),(min-device-pixel-ratio:3){
div::after{
width: 300%;
height: 300%;
-webkit-transform: scale(.33333);
transform: scale(.33333);
/*border-radius: $radius * 3;有圆角*/
}
}
/**
* @module 背景与边框
* @description 为元素添加边框(包括1px边框)
* @method border
* @version 2.0.0
* @param {String} $border-width 指定边框厚度(单位为px),默认值:1px,取值与`border-width`属性一致,不同方向代表边框位置 <2.0.0>
* @param {String} $border-color 指定边框颜色 <2.0.0>
* @param {String} $border-style 指定边框样式 <2.0.0>
* @param {String} $radius 指定边框圆角半径,默认值:null <2.0.0>
*/
@mixin border($border-width: 1px, $border-color: map-get($base, border-color), $border-style: solid, $radius: null,$opacity: null) {
// 为边框位置提供定位参考
position: relative;
@if $border-width == null {
$border-width: 0;
}
border-radius: $radius;
&::after {
// 用以解决边框layer遮盖内容
pointer-events: none;
position: absolute;
z-index: 999;
top: 0;
left: 0;
// fix当元素宽度出现小数时,边框可能显示不全的问题
// overflow: hidden;
content: "\0020";
border-color: $border-color;
border-style: $border-style;
border-width: $border-width;
@if $opacity != null {
opacity: $opacity;
}
// 适配dpr进行缩放
@media (-webkit-min-device-pixel-ratio:1),(min-device-pixel-ratio:1){
width: 100%;
height: 100%;
@if $radius != null {
border-radius: $radius;
}
}
@media (-webkit-min-device-pixel-ratio:2),(min-device-pixel-ratio:2){
width: 200%;
height: 200%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
@if $radius != null {
border-radius: $radius * 2;
}
}
@media (-webkit-min-device-pixel-ratio:2),(min-device-pixel-ratio:2){
width: 200%;
height: 200%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
@if $radius != null {
border-radius: $radius * 2;
}
}
@media (-webkit-min-device-pixel-ratio:2),(min-device-pixel-ratio:3){
width: 300%;
height: 300%;
-webkit-transform: scale(0.33333);
transform: scale(0.33333);
@if $radius != null {
border-radius: $radius * 3;
}
}
-webkit-transform-origin: (0,0);
transform-origin:(0 0);
}
}
div {
position: relative;
border: none;
}
div:after {
content: '';
position: absolute;
left: 0;
background: #000;
width: 100%;
height: 1px;
transform: scaleY(0.5);/*以dpr = 2为例 */
transform-origin: 0 0;
}