CSS 实现居中 + 清除浮动
一、水平居中
1、行内元素:text-align:center;
2、块级元素:margin:0 auto;
3、绝对定位和移动:absolute + transform
4、绝对定位和负边距:absolute + margin
5、flex布局:flex + justify-content:center
二、垂直居中
1、子元素为单行文本:line-height:一定height / padding
2、绝对定位和移动:absolute + transform
3、绝对定位和负边距:absolute + margin
4、flex布局:flex + align-items:center
5、table:display:table-cell; vertical-align:middle;
三、水平垂直居中
1、已知元素宽高:绝对定位 + margin:auto
width:200px;height:200px;
position:absolute;left:0;right:0;top:0;bottom:0;
margin:auto;
2、已知元素宽高:绝对定位 + 负margin
width:200px;height:200px;
position:absolute;left:50%;top:50%;
margin-top:-100px;margin-left:-100px;
3、absolute + transform
position:absolute; left:50%; top:50%;
transform:translate(50%, 50%) 自己的50%;
4、flex + justify-content + align-items
display:flex;
justify-content:center;
align-items:center;
5、grid + margin
body,html{ height:100%; display:grid;}
span{ margin:auto;}
四、清除浮动的常见方法:
1、给父元素增加高度(height),只适用于高度固定的布局
2、在标签的结尾处增加空的div标签,clear:both
不利于代码语义化,不利于页面优化与维护
3、给父级div定义伪类:after和zoom
.clearfix:after{display:block; clear:both; content:""; visibility:hidden; height:0;}
.clearfix{zomm:1}
4、给父级元素增加样式:overflow:hidden
不能和position配合使用,因为超过的部分会被隐藏。