移动端布局

移动端布局的出发点是页面内容根据手机浏览器宽度自动缩放, 使得页面布局效果可以保持一致 超大屏手机可能会有点老年机的感觉?

ps:选择rem而不是vw是出于兼容性的考虑.

首先例行惯例吧viewport 设置好

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">


rem布局是相对html节点的font-size来作为标准, 于是不同的手机需要设置不同的html font-size, 这个可以通过js 来实现, 下面的代码是假设设计稿尺寸为640px的前提.

flexible.js

// 插入head中第一个script标签
(function () {
    var htmlElement = document.querySelector('html');
    htmlElement.style.display = 'none';  // 防止页面闪动
 
    // decided by the width of design page
    var designWidth = 640; 
 
    function initSize() {
        var deviceWidth = document.documentElement.clientWidth;  // 设备宽度
        if(deviceWidth > designWidth) deviceWidth = designWidth;  // 设置最大尺寸
        document.documentElement.style.fontSize = deviceWidth / (designWidth/100.0) + 'px';  // 设置html font-size
    }
    initSize();
    htmlElement.style.display = 'block';
 
    window.addEventListener('resize', function () {
        initSize();
    })
})();

假设浏览器宽度为640 (和设计稿宽度相同), 那么font-size 就是 100px, 此时例如要设置margin-left: 10px 就是对应写成0.1rem.  

但布局的时候做这样的转换会很麻烦. 用sass 写一个转换函数可以方便我们书写样式.

@function pxRem($px) {
    $baseFontSize: 100px;
    @return $px / $baseFontSize * 1rem;
}
 
// 使用
.landing-footer {
    color: #ccc;
    margin-top: pxRem(70px);
    height: pxRem(82px);
    line-height: pxRem(82px);
}

此外如果想在pc上限制宽度的话, body 需要设置一个额外样式:

body {
    width: 6.4rem;  // 最大宽度 640px, 根据设计稿决定.
    margin: 0 auto;
}

最后说下字体的问题. 

除非网页用到了特殊的点阵字体(位图字体), 一般网页使用rem为单位设置字体大小是没有问题的.

另外需要注意chrome中的最小字体是12px, 需要和设计师有所沟通.

body {  // 覆盖html的font-size
    font-size: pxRem(14px);  // 设置默认大小
}
 
.element {
    font-size: pxRem(20);
}


如果需要在html 上使用 .font-12, .font-14 之类的样式的话, 可以通过sass预先创建好

@for $fontSize from 12 through 48 {
    .font-#{$fontSize} {
        font-size: pxRem(#{$fontSize}px);
    }
}
<p class="content font-14">中饭吃什么 </p>
原文地址:https://www.cnblogs.com/tangkikodo/p/5937940.html