css笔记

56 阅读1分钟

1px问题

移动端1px问题是指在高分辨率屏幕(如Retina屏)上,CSS中的1px边框看起来比实际需要的粗,这是因为设备像素比(devicePixelRatio)大于1导致的。在devicePixelRatio为2的屏幕上,1个CSS像素实际对应2个物理像素,所以1px的边框实际渲染为2px,看起来偏粗。

解决方案:使用transform缩放+媒体查询适配不同DPR

// 横线
.box {
        position: relative;
        width: 100px;
      }
​
      .box::after {
        content: "";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 1px;
        background: red;
        transform: scaleY(0.5);
        transform-origin: 0 0;
      }
​
      /* 针对不同DPR的适配 */
      @media (-webkit-min-device-pixel-ratio: 2) {
        .box::after {
          transform: scaleY(0.5);
        }
      }
​
      @media (-webkit-min-device-pixel-ratio: 3) {
        .box::after {
          transform: scaleY(0.33);
        }
      }
// 竖线
.box {
  position: relative;
  width: 100px;
  height: 100px; /* 给容器设置高度 */
}
.box::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0; /* 改为top: 0 */
  width: 1px; /* 宽度改为1px */
  height: 100%; /* 高度改为100% */
  background: red;
  transform: scaleX(0.5); /* 改为scaleX缩放 */
  transform-origin: 0 0; /* 或者用 left top */
}