Hello, Boswell!
  • 移动端 1 像素问题及解决办法

移动端 1 像素问题及解决办法

问题

在移动端 web 开发中,UI 设计稿中设置边框为 1 像素,前端在开发过程中如果出现 border:1px,测试会发现在某些机型上,1px 会比较粗,即是较经典的移动端 1px 像素问题?

原因

  1. 当设备像素比不为 1 时,1css 像素不再是 1 物理像素;

解决方案

  1. 使用背景颜色;

  2. 获取机器的设备像素比,使用 js 动态设置像素大小;

  3. 设置 1px 的渐变背景,50%有颜色,50%透明

.border {
  background: linear-gradient(180deg, black, black 50%, transparent 50%) top left /
      100% 1px no-repeat, linear-gradient(
        90deg,
        black,
        black 50%,
        transparent 50%
      ) top right / 1px 100% no-repeat,
    linear-gradient(0, black, black 50%, transparent 50%) bottom right / 100% 1px
      no-repeat, linear-gradient(-90deg, black, black 50%, transparent 50%) bottom
      left / 1px 100% no-repeat;
}
  1. box-shadow
.shadow {
  -webkit-box-shadow: 0 1px 1px -1px rgba(255, 0, 0, 0.5);
  box-shadow: 0 1px 1px -1px rgba(255, 0, 0, 0.5);
}
  1. viewport 合 rem 结合
<meta
  name="viewport"
  content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no"
/>
<meta
  name="viewport"
  content="initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no"
/>
  1. 使用:before,或者:after 伪元素来模拟边框
.scale-1px {
  position: relative;
  border: none;
}

.scale-1px:after {
  content: '';
  position: absolute;
  bottom: 0;
  background: #000;
  width: 100%;
  height: 1px;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
}
.scale-1px {
      position: relative;
      margin-bottom: 20px;
  border: none;
}
.scale-1px:after {
      content: '';
      position: absolute;
  top: 0;
      left: 0;
      border: 1px solid #000;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      width: 200%;
      height: 200%;
      -webkit-transform: scale(0.5);
      transform: scale(0.5);
      -webkit-transform-origin: left top;
      transform-origin: left top;
}

还是要根据设备像素比来处理:

if (window.devicePixelRatio && devicePixelRatio >= 2) {
  document.querySelector('div').className = 'scale-1px';
}
Last Updated:
Contributors: mingzhuang.ji