- Problem Description:
In order to adapt to various screens, we usually use device independent pixels to layout the page when we write code.
On the screen with the device pixel ratio greater than 1, the 1px we wrote is actually rendered by multiple physical pixels, which will cause the phenomenon that 1px looks thick on some screens.
- There are the following solutions:
@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); } } } } }
This way can satisfy all kinds of scenes.
- Usage:
Step 1: @ include border-1px(blue, all); introduce the code block defined by mixin (create pseudo class to simulate border)
Step 2: < div class = "border-1px-all" >
- * Note:
Why there is no direct operation on the border width is because some models do not support the value of 0.5px, which will be treated as 0, so scaling is used.