html5移动端适配使用流体布局经常遇到的坑

来源:互联网 发布:mac python 编辑:程序博客网 时间:2024/04/29 17:09

以如下布局为例:
这里写图片描述

相应的布局如下:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>流体布局</title>    <style type="text/css">        body,ul{            margin: 0;padding: 0;        }        ul{            list-style: none;        }        .top{            height: 50px;            text-align: center;            background-color: gold;            line-height: 50px;        }        ul li{            width: 25%;            height: 50px;            background-color: cyan;            float: left;            text-align: center;            line-height: 50px;            border: 2px solid #ccc;        }    </style></head><body>    <div class="top">顶部导航</div>    <ul>        <li>1</li>        <li>2</li>        <li>3</li>        <li>4</li>    </ul></body></html>

可是运行结果如下:
这里写图片描述
为什么呢,因为border占用的像素,也被算在整个宽度中,所以4被挤下来了。。。
运用流体布局的第一个方法:使用样式中的计算函数 calc() 来设置宽度。。。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>流体布局</title>    <style type="text/css">        body,ul{            margin: 0;padding: 0;        }        ul{            list-style: none;        }        .top{            height: 50px;            text-align: center;            background-color: gold;            line-height: 50px;        }        ul li{            width: calc(25%-4px);            height: 50px;            background-color: cyan;            float: left;            text-align: center;            line-height: 50px;            border: 2px solid #ccc;            /*box-sizing: border-box;*/        }    </style></head><body>    <div class="top">顶部导航</div>    <ul>        <li>1</li>        <li>2</li>        <li>3</li>        <li>4</li>    </ul></body></html>

结果如下:
这里写图片描述
这又是为什么呢?这里有好大的一个坑。。。
width: calc(25%-4px);----这个地方减号前后都要加空格,悲伤。。。修改以后,恢复正常。。。
当然,在使用流体布局时,不建议使用calc函数,建议使用流体布局的第二种方法: box-sizing
1、content-box 默认的盒子尺寸计算方式
2、border-box 置盒子的尺寸计算方式为从边框开始,盒子的尺寸,边框和内填充算在盒子尺寸内;
使用 box-sizing 达到上述布局代码如下:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>流体布局</title>    <style type="text/css">        body,ul{            margin: 0;padding: 0;        }        ul{            list-style: none;        }        .top{            height: 50px;            text-align: center;            background-color: gold;            line-height: 50px;        }        ul li{            width: 25%;            height: 50px;            background-color: cyan;            float: left;            text-align: center;            line-height: 50px;            border: 2px solid #ccc;            box-sizing: border-box;        }    </style></head><body>    <div class="top">顶部导航</div>    <ul>        <li>1</li>        <li>2</li>        <li>3</li>        <li>4</li>    </ul></body></html>

当然在适配移动端时除了流体布局外,还有响应式布局和基于rem的布局,后续遇到坑再总结。。。

1 0
原创粉丝点击