CSS的常見布局
CSS常見布局使用display屬性(文檔流)+position屬性(定位)+float屬性(浮動)。
inline-block
display:inline-block屬性既可以像行級元素一樣水平分布,也可以像塊級元素一樣設(shè)置寬高,如果空間夠就可以實現(xiàn)左右布局。
float(應(yīng)用較廣)
給要并排的子元素加上style=float:left(或right),他們的父元素添加class:clearfix,即可脫離文檔流,實現(xiàn)排排坐。clearfix的css為
.clearfix::after { content=" "; display:block; clear:both;}
flex(不能兼容ie)
flex是一種新的布局方式
a. flex布局與方向無關(guān)
b. 可實現(xiàn)空間的自動分配、自動對齊
1、左右布局
float百分比布局
.clearfix::after{content:' ';display:block;clear:both; }
.left{float:left;height:200px;width:2%;background: red; }
.right{float:left;height:200px;width:8%;background: blue; }
注:用于布局的div中不要添加其他margin、padding等,需要的話在里面再加元素。
flex布局
.content{display:flex; }
.left{float:left;height:200px;width:100px;background: red; }
.right{float:left;height:200px;background: blue;flex-grow:1; }
2、左中右布局
flex布局
.content{display:flex; }
.middle{height:200px;background:yellow;flex-grow:1;margin:010px; }
.left{height:200px;width:100px;background:red; }
.right{height:200px;width:150px;background:blue; }
3、水平居中:
div的左右margin為auto
內(nèi)聯(lián)元素的父元素加上text-align:center;
4、垂直居中:單行元素line-height跟height相等就垂直居中
line-height+padding
5、flex的完美居中
display:flex;justify-content:center;align-items:center;