1. The problem of 1PX on mobile terminal

CSS 1px is 1px on PC; On mobile, it’s usually more than 1px. Do not believe you can test yourself!

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Mobile 1px issues</title>
    <style>
        body {
            margin: 0;
            padding: 19px
        }
        div {
            padding: 1em;
            margin: 1em;
        }
        .box1 {
            border-top: 1px solid # 000;
        }
        .box2 {
            border-bottom: 1px solid # 000;
        }
    </style>
</head>

<body>
    <div class="box1">1px top border</div>

    <div class="box2">0.5px top border</div>
</body>

</html>
Copy the code

Two, causes

  • DevicePixelRatio: DPR =window.devicePixelRatio, which is the ratio of physical pixels to logical pixels of the device.
  • inretinaScreen on my phone,dprfor2or3.cssWriting in the1pxThe width is mapped to a physical pixel2pxor3pxWidth.
  • Such as:iPhone6thedprfor2, the physical pixel is750(X-axis), its logical pixels are375. In other words, 1 logical pixel atxAxis andyIn the axial direction, two physical pixels are required for display. That is, when DPR =2, one CSS pixel consists of four physical pixels.

Iii. Solutions:Pseudo-element + Transform scaling

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Mobile 1px issues</title>
    <style>
        body {
            margin: 0;
            padding: 19px
        }
        div {
            padding: 1em;
            margin: 1em;
        }
        .box1 {
            border-top: 1px solid # 000;
        }
        .box2 {
            position: relative;
            /* border-bottom: 1px solid #000; * /
        }
        /* set a 0.5px border */ to box2's bottom border
        .box2::after {
            content: ' ';
            position: absolute;
            left: 0;
            bottom: 0;
            width: 100%;
            height: 1px;
            background-color: # 000;
            transform: scaleY(0.5);
        }
    </style>
</head>

<body>
    <div class="box1">1px top border</div>

    <div class="box2">0.5px bottom border</div>
</body>

</html>
Copy the code