爲了適配各類屏幕,咱們寫代碼時通常使用設備獨立像素來對頁面進行佈局。
而在設備像素比大於 1的屏幕上,咱們寫的 1px其實是被多個物理像素渲染,這就會出現 1px在有些屏幕上看起來很粗的現象。web
@mixin border-1px($color, $direction) { position: relative; &::before { content: ""; position: absolute; z-index: 1; @if $direction==all { left: 0; top: 0; border: 1px solid $color; box-sizing: border-box; transform-origin: left top; } @else { background-color: $color; @if $direction==top { left: 0; top: 0; width: 100%; height: 1px; } @if $direction==right { right: 0; top: 0; width: 1px; height: 100%; } @if $direction==bottom { left: 0; bottom: 0; width: 100%; height: 1px; } @if $direction==left { left: 0; top: 0; width: 1px; height: 100%; } } } } @each $direction in all, top, right, bottom, left { @for $i from 1 to 10 { $scale: 1 / $i; @media only screen and (-webkit-min-device-pixel-ratio:$i) { .border-1px-#{$direction}::before { @if $direction==all { width: $i * 100%; height: $i * 100%; transform: scale($scale); } @if $direction==top { transform: scaleY($scale); } @if $direction==bottom { transform: scaleY($scale); } @if $direction==right { transform: scaleX($scale); } @if $direction==left { transform: scaleX($scale); } } } } }
這種方式能夠知足各類場景。佈局
第一步:@include border-1px(blue, all);引入由mixin定義的代碼塊(建立僞類 模擬border)
第二步:<div class="border-1px-all"></div>添加border-1px-#{$direction}類名(縮放尺寸)code
爲什麼沒有直接對border-width直接操做 是由於有部分機型不支持0.5px這樣的值 會被當成0來處理 故用縮放來實現。orm