1. 程式人生 > >CSS 0.5px 細線邊框的原理和實現方式

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

bottom back 先決條件 device min style ati 而且 origin

  細線邊框的具體實現方法有:偽元素縮放或漸變,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 細線邊框的原理和實現方式