3栏布局技巧
-
流体布局
主要内容无法优先加载,影响用户体验
html结构,left,right,center,主要内容无法优先加载
<div class="container1"> <div class="col_left">left</div> <div class="col_right">right</div> <div class="col_center">center</div> </div>
css
/* 左右浮动,中间加 margin */ .col_left { width: 100px; background: rgb(7, 78, 119); float: left; } .col_right { width: 100px; background: rgb(39, 20, 20); float: right; } .col_center { height: 300px; background: green; margin: 0 100px; /* ********大小等于侧边 width */ }
-
BFC3栏布局
主要内容无法优先加载,影响用户体验
<div class="container1"> <div class="col_left">left</div> <div class="col_right">right</div> <div class="col_center">center</div> </div>
css
.col_left { width: 100px; height: 100px; background: red; float: left; /* 左浮动*/ } .col_right { width: 100px; height: 100px; background: green; float: right; /*右浮动*/ } .col_center { height: 200px; background: blue; overflow: hidden; /*块级格式化上下文 BFC */ }
-
双飞翼布局
利用的是浮动元素 margin 负值的应用。主体内容可以优先加载,
HTML 代码结构稍微复杂点。<div class="content"> <div class="main"></div> </div> <div class="left"></div> <div class="right"></div>
css
.content { float: left; width: 100%; /*设置宽度,使得剩下元素下移*/ } .main { height: 200px; margin-left: 110px; margin-right: 220px; background-color: green; } .left { float: left; height: 200px; width: 100px; margin-left: -100%; background-color: red; } .right { width: 200px; height: 200px; float: left; margin-left: -200px; background-color: blue; }
-
圣杯布局
<div class="container"> <div class="main"></div> <div class="left"></div> <div class="right"></div> </div>
css
.container { margin-left: 120px; /*设置盒子大小*/ margin-right: 220px;/*设置盒子大小*/ } .main { float: left; width: 100%; /*设置盒子大小*/ height: 300px; background-color: red; } .left { float: left; width: 100px; height: 300px; margin-left: -100%; position: relative; /*相对定位*/ left: -120px; /**/ background-color: blue; } .right { float: left; width: 200px; height: 300px; margin-left: -200px; position: relative; /**/ right: -220px; /**/ background-color: green; }
-
Flex 布局
<div class="container"> <div class="main"></div> <div class="left"></div> <div class="right"></div> </div>
css
.container { display: flex; } .main { flex-grow: 1; height: 300px; background-color: red; } .left { order: -1; /**/ flex: 0 1 200px; margin-right: 20px; height: 300px; background-color: blue; } .right { flex: 0 1 100px; margin-left: 20px; height: 300px; background-color: green; }
-
绝对定位
<div class="container"> <div class="main"></div> <div class="left"></div> <div class="right"></div> </div>
.container { position: relative; } .main { height: 400px; margin: 0 120px; background-color: green; } .left { position: absolute; width: 100px; height: 300px; left: 0; top: 0; background-color: red; } .right { position: absolute; width: 100px; height: 300px; background-color: blue; right: 0; top: 0; }