移动端border:1px问题解决方案

  • 问题描述:

为了适配各类屏幕,咱们写代码时通常使用设备独立像素来对页面进行布局。
而在设备像素比大于 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

相关文章
相关标签/搜索