1px
边框
July 25, 2024 by
优先使用 伪类和定位
处理1像素边框问题
为啥 border
是 1px
呢
在 CSS
中, 边框可以设置为 0.5px
, 但在某些情况下, 尤其是低分辨率的屏幕上, 浏览器可能会将其渲染为 1px
或根本不显示。这是因为某些浏览器和显示设备不支持小于 1px
的边框宽度或不能准确渲染出这样的细小边框
浏览器渲染机制
- 不同浏览器对于小数像素的处理方式不同. 一些浏览器可能会将
0.5px
边框四舍五入为1px
, 以确保在所有设备上的一致性
设备像素比
- 在高 DPI (如 Retina 显示器) 设备上,
0.5px
边框可能看起来更清晰, 因为这些设备可以渲染更细的边框 - 在低 DPI 设备上,
0.5px
边框可能会被放大或者根本不会被显示
解决方案
-
使用伪类和定位
css 伪类和定位.active { color: rgba(250, 100, 0, 1); font-size: 14px; position: relative; } .active::after { content: ""; pointer-events: none; display: block; position: absolute; left: 0; top: 0; transform-origin: 0 0; border: 1px #ff892e solid; box-sizing: border-box; width: 100%; height: 100%; }
推荐使用 -
使用阴影, 使用
F12
看的时候感觉还是有些问题css 阴影.active2 { margin-left: 10px; color: rgba(250, 100, 0, 1); font-size: 14px; position: relative; box-shadow: 0 0 0 0.5px #ff892e; }
-
使用
svg
, 但这种自己设置了宽度html svg<div class="active"> <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="none"> <rect x="0" y="0" width="100" height="100" fill="none" stroke="#ff892e" stroke-width="0.5"></rect> </svg> active </div>
-
使用
svg
加定位, 也比较麻烦, 而且有其他的问题html svg+定位<div class="active"> <svg viewBox="0 0 100 100" preserveAspectRatio="none"> <rect x="0" y="0" width="100" height="100" fill="none" stroke="#ff892e" stroke-width="0.5"></rect> </svg> <div class="content">active</div> </div>
css svg+定位.active { color: rgba(250, 100, 0, 1); font-size: 14px; position: relative; display: inline-block; } .active svg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; box-sizing: border-box; } .active .content { position: relative; z-index: 1; }
-
使用一个父元素, 比较麻烦
html 父元素<div class="border-container"> <div class="active">active</div> </div>
css 父元素.border-container { display: inline-block; padding: 0.5px; background-color: #ff892e; } .active { color: rgba(250, 100, 0, 1); font-size: 14px; background-color: white; }