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,本文原創,著作權歸作者所有,轉載請註明原鏈接及出處。

更多精彩文章,請掃下方二維碼關注我的公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章