左侧栏固定右侧栏自适应的布局在开发过程中真的可谓是屡见不鲜, 今天我们就来聊聊这个司空见惯的布局方式... 啦啦啦...
首先把 html 的基本骨架写出来, 代码如下:
- <p class="container">
- <p class="left"></p>
- <p class="right"></p>
- </p>
第一种: 左侧浮动, 右侧宽度百分比, margin-left 为左侧栏的宽度值
- html,body{
- height: 100%;
- margin: 0;
- padding: 0;
- }
- p.container{
- height: 100%;
- width: 100%;
- background-color: ghostwhite;
- }
- p.left{
- height: 100%;
- width: 300px;
- float: left;
- background-color: deeppink;
- }
- p.right{
- width: 100%;
- background-color: aqua;
- height: 100%;
- margin-left: 300px;
- }
第二种: 子绝父相, 父亲设置相对定位, 儿子设置绝对定位, 左侧宽度固定, 右侧栏还是和第一种一样
- html,body{
- height: 100%;
- margin: 0;
- padding: 0;
- }
- p.container{
- height: 100%;
- width: 100%;
- background-color: ghostwhite;
- position: relative;
- }
- p.left{
- height: 100%;
- width: 300px;
- position: absolute;
- left: 0px;
- background-color: deeppink;
- }
- p.right{
- width: 100%;
- background-color: aqua;
- height: 100%;
- margin-left: 300px;
- }
第三种: 通过给右侧栏设置 overflow:hidden, 触发 BFC, 什么是你 BFC? 简单说就是一个块级元素不会和别的浮动元素进行重叠
- p.container{
- height: 100%;
- width: 100%;
- background-color: ghostwhite;
- }
- p.left{
- height: 100%;
- width: 300px;
- float:left;
- background-color: deeppink;
- }
- p.right{
- width: 100%;
- background-color: aqua;
- height: 100%;
- overflow:hidden;
- }
第四种: 左侧栏 float:left, 右侧栏 float:right, 右侧栏设置负边距, margin 的负边距博大精深!
- p.container{
- height: 100%;
- width: 100%;
- background-color: ghostwhite;
- }
- p.left{
- height: 100%;
- width: 300px;
- float:left;
- background-color: deeppink;
- }
- p.right{
- width: 100%;
- background-color: aqua;
- height: 100%;
- float: right;
- margin-right: -300px;
- }
第五种: 使用 flex 弹性布局, 把 container 设置为 flex 即可
- p.container{
- height: 100%;
- width: 100%;
- background-color: ghostwhite;
- display: flex;
- }
- p.left{
- height: 100%;
- width: 300px;
- background-color: deeppink;
- }
- p.right{
- width: 100%;
- background-color: aqua;
- height: 100%;
- }
第六种: 使用 table 布局进行实现, 外层设置 display: table, 内层设置 display:table-cell, 就是等高布局了, 但是右侧不能设置宽度才行!
- p.container{
- height: 100%;
- width: 100%;
- background-color: ghostwhite;
- display: table;
- }
- p.left{
- height: 100%;
- width: 300px;
- background-color: deeppink;
- display: table-cell;
- }
- p.right{
- background-color: aqua;!
- height: 100%;
- display: table-cell;
- }
上述所有的内容都经过本人亲自测试
真心的希望能对大家在布局方面有所帮助!!! 相互学习一起提高!
来源: https://www.2cto.com/kf/201806/751355.html