CSS 0.5px 細線邊框的原理和實現方式


  細線邊框的具體實現方法有:偽元素縮放或漸變,box-shadow模擬,svg畫線,border-image裁剪等。要實現小於1px的線條,有個先決條件:屏幕的分辨率要足夠高,設備像素比要大於1,即css中的1個像素對應物理屏幕中1個以上的像素點。

  對於普通電腦,屏幕物理像素和css像素一一對應,顯示的最小單位就是1px。而現在的手機,屏幕物理寬度一般都大於頁面顯示寬度。例如蘋果6s的屏幕分辨率為1334x750像素,但是以375px的寬度顯示頁面,設備像素比就是750/375=2;此時在css中定義0.5px的寬度,實際上對應物理屏幕的1個像素點,這就是border小於1px的的實現基礎。

 1 <!-- @media鑒別設備像素比 -->
 2 <style>
 3 @media only screen and (-webkit-min-device-pixel-ratio: 2){
 4   .fineLine{
 5     -webkit-transform: scaleY(.5);
 6   }
 7 }
 8 </style>
 9  
10 <!-- js獲取設備像素比 -->
11 <script type="text/javascript">
12   var dpr = window.devicePixelRatio;
13   // 如下方法精確計算出了物理設備與css的像素比dppx。但實際使用中dpr更廣泛,也足以滿足一般需求
14   var dppx = window.screen.width/(window.innerWidth || document.documentElement.clientWidth);
15 </script>

 

一、縮放biefore/after偽元素

  偽元素進行絕對定位,background着色要優於border着色,適合畫單線條:

 1 <div class="fineLine"></div>
 2 <!-- fineLine的:before為上邊框,:after為下邊框 -->
 3 <style type="text/css">
 4 .fineLine {
 5     position: relative;
 6 }
 7 .fineLine:before,.fineLine:after{
 8   position: absolute;
 9   content: " ";
10   height: 1px;
11   width: 100%;
12   left: 0;
13   transform-origin: 0 0;
14   -webkit-transform-origin: 0 0;
15 }
16 .fineLine:before {
17     top: 0;
18     background: #000;
19 }
20 .fineLine:after {
21     bottom: 0;
22     border-bottom: 1px solid #000;
23 }
24 @media only screen and (-webkit-min-device-pixel-ratio: 1.5) {
25     .fineLine:after,.fineLine:before {
26         -webkit-transform: scaleY(.667);
27     }
28 }
29 @media only screen and (-webkit-min-device-pixel-ratio: 2) {
30     .fineLine:after,.fineLine:before {
31         -webkit-transform: scaleY(.5);
32     }
33 }
34 </style>

 

 

二、box-shadow模擬

  box-shaodw適合模擬box四周都需要細線border的情況,而且支持border-radius。此例中演示的是dppx鑒別:

 1 <div class="fineLine"></div>
 2  
 3 <style type="text/css">
 4 .fineLine {
 5     box-shadow: 0 0 0 1px;
 6 }
 7 @media (min-resolution: 2dppx) {
 8     .fineLine {
 9         box-shadow: 0 0 0 0.5px;
10     }
11 }
12 @media (min-resolution: 3dppx) {
13     .fineLine {
14         box-shadow: 0 0 0 0.33333333px;
15     }
16 }
17 </style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM