CSS布局
CSS的常见布局
CSS常见布局使用display属性(文档流)+position属性(定位)+float属性(浮动)。
inline-block
display:inline-block属性既可以像行级元素一样水平分布,也可以像块级元素一样设置宽高,如果空间够就可以实现左右布局。
float(应用较广)
给要并排的子元素加上style=float:left(或right),他们的父元素添加class:clearfix,即可脱离文档流,实现排排坐。clearfix的css为
.clearfix::after { content=" "; display:block; clear:both;}
flex(不能兼容ie)
flex是一种新的布局方式
a. flex布局与方向无关
b. 可实现空间的自动分配、自动对齐
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
内联元素的父元素加上text-align:center;
4、垂直居中:单行元素line-height跟height相等就垂直居中
line-height+padding
5、flex的完美居中
display:flex;justify-content:center;align-items:center;