用CSS画一条0.5px的线
上次面试前端被问到了这个问题,感觉有点懵懵的,我就回答了一个scaleY(0.5),这个是真的没想到,希望有需要的朋友可以去看看。随便记住一种就行。
1.第一种方式:通过缩放1px的线条实现视觉上的0.5px效果,兼容性较好。
.thin-line {
position: relative;
}
.thin-line::after {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 1px; /* 初始高度1px */
background: #000;
transform: scaleY(0.5); /* 垂直缩放至0.5倍 */
transform-origin: 0 0; /* 确保缩放基点正确 */
}
2.第二种方式:直接使用0.5px边框(现代浏览器)
.thin-border {
border-bottom: 0.5px solid #000;
}
3.第三种方式:使用transform缩放(推荐) 结合媒体查询(适配高分辨率屏幕)
.thin-line::after {
content: '';
/* ...同方法1... */
}
/* 高分辨率设备直接使用0.5px */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) {
.thin-line::after {
border-bottom: 0.5px solid #000;
transform: none; /* 禁用缩放 */
}
}
4.第四种方式:线性渐变:创建极细渐变模拟线条,适合简单场景。
.thin-gradient {
background: linear-gradient(to bottom, #000 50%, transparent 50%);
height: 1px;
transform: scaleY(0.5);
}
5.第五种方式:box-shadow:利用微小阴影模拟线条。
.thin-shadow {
box-shadow: 0 0.5px 0 #000;
}