CSS 移动端 1px(线条/边框) 解决方案

由于不同的手机有不同的像素密度导致的。如果移动显示屏的分辨率始终是普通屏幕的2倍,1px的边框在devicePixelRatio=2的移动显示屏下会显示成2px,所以在高清瓶下看着1px总是感觉变胖了

小编阅读过其他作者的文章中有写 0.5px 的写法,在理论上最小的单位是 1px。 所以会出现有的设备写 0.5px 无效(没有边框)的情况。

如何使用正确的 1px单位 又能在移动设备上显示 1px 的效果呢?

本文将介绍使用 CSS3  的 transform 属性的 scale 值来解决这个问题,这也是最常用的解决方案。下方的源码中说明 1px(线条/边框) 解决方案

效果对比(图片效果有点问题,请复制下方源码查看最终效果

源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="author" content="[email protected]">
    <title>移动端 1px(线条/边框) 解决方案</title>
    <style type="text/css">
        body{
            margin: 0;
            padding: 0;
            font-size: 14px;
            color: #333;
            font-family: 'Microsoft YaHei', 'Times New Roman', Times, serif;
        }

        /* 线条 */
        .list{
            margin: 0 20px;
            list-style: none;
            line-height: 42px;
            padding: 0;
        }
        .list>li{
            padding: 0;
            position: relative;
        }
        .list>li:not(:first-child):after{   /* CSS匹配非第一个直接子元素 */
            content: "";
            display: block;
            height: 0;
            border-top: #999 solid 1px;
            width: 100%;
            position: absolute;
            top: 0;
            right: 0;
            transform: scaleY(0.5); /* 将 1px 的线条缩小为原来的 50% */
        }

        /* 边框 */
        /* 
            其他作者可能会通过设置4个边的线条凑出边框线的效果,
            这样做不仅代码不够精简,而且调整圆角问题也会非常麻烦
        */
        .button{
            line-height: 42px;
            text-align: center;
            margin: 20px;
            background-color: #f8f8f8;
            position: relative;
            border-radius: 4px;
        }
        .button:after{
            content: "";
            position: absolute;
            top: -50%;
            right: -50%;
            bottom: -50%;
            left: -50%;
            border: 1px solid #999;
            transform: scale(0.5);
            transform-origin: 50% 50% 0;
            box-sizing: border-box;
            border-radius: 8px; /* 尺寸缩小 50%,即圆角半径设置为按钮的2倍 */
        }
    </style>
</head>
<body>
<ul class="list">
    <li>线条 1px</li>
    <li>web前端 河浪</li>
    <li>[email protected]</li>
</ul>
<div class="button">边框 1px</div>
</body>
</html>

作者:黄河爱浪 QQ:1846492969,邮箱:[email protected]

公众号:web-7258,本文原创,著作权归作者所有,转载请注明原链接及出处。

更多精彩文章,请扫下方二维码关注我的公众号

发布了112 篇原创文章 · 获赞 24 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/u013350495/article/details/102547553
今日推荐