细线边框的具体实现方法有:伪元素缩放或渐变,box-shadow模拟,svg画线,border-image裁剪等。要实现小于1px的线条,有个先决条件:屏幕的分辨率要足够高,设备像素比要大于1,即css中的1个像素对应物理屏幕中1个以上的像素点。
对于普通电脑,屏幕物理像素和css像素一一对应,显示的最小单位就是1px。而现在的手机,屏幕物理宽度一般都大于页面显示宽度。例如苹果6s的屏幕分辨率为1334x750像素,但是以375px的宽度显示页面,设备像素比就是750/375=2;此时在css中定义0.5px的宽度,实际上对应物理屏幕的1个像素点,这就是border小于1px的的实现基础。
<!-- @media鉴别设备像素比 --><style>@media only screen and (-webkit-min-device-pixel-ratio: 2){ ?.fineLine{ ???-webkit-transform: scaleY(.5); ?}}</style><!-- js获取设备像素比 --><script type="text/javascript"> ?var dpr = window.devicePixelRatio; ?// 如下方法精确计算出了物理设备与css的像素比dppx。但实际使用中dpr更广泛,也足以满足一般需求 ?var dppx = window.screen.width/(window.innerWidth || document.documentElement.clientWidth);</script>
一、缩放biefore/after伪元素
伪元素进行绝对定位,通过border或者background着色,适合画单线条:
?<div class="fineLine"></div> ?<style type="text/css"> ?.fineLine { ?????position: relative; ?} ?.fineLine:before,.fineLine:after{ ???position: absolute; ???content: " "; ???height: 1px; ???width: 100%; ???left: 0; ???transform-origin: 0 0; ???-webkit-transform-origin: 0 0; ?} ?.fineLine:before { ?????top: 0; ?????background: #000; ?} ?.fineLine:after { ?????bottom: 0; ?????border-bottom: 1px solid #000; ?} ?@media only screen and (-webkit-min-device-pixel-ratio: 1.5) { ?????.fineLine { ?????????-webkit-transform: scaleY(.667); ?????} ?} ?@media only screen and (-webkit-min-device-pixel-ratio: 2) { ?????.fineLine { ?????????-webkit-transform: scaleY(.5); ?????} ?} ?</style>
二、box-shadow模拟
box-shaodw适合模拟box四周都需要细线border的情况,而且支持border-radius。此例中演示的是dppx鉴别:
?<div class="fineLine"></div> ?<style type="text/css"> ?.fineLine { ?????box-shadow: 0 0 0 1px; ?} ?@media (min-resolution: 2dppx) { ?????.fineLine { ?????????box-shadow: 0 0 0 0.5px; ?????} ?} ?@media (min-resolution: 3dppx) { ?????.fineLine { ?????????box-shadow: 0 0 0 0.33333333px; ?????} ?} ?</style>
CSS 0.5px 细线边框的原理和实现方式
原文地址:https://www.cnblogs.com/yangshifu/p/9257519.html