垂直居中
1.行内元素:line-height与height值保持一致即可【仅对单行文本生效】
// 父元素 height: 200px; line-height: 200px;
水平垂直居中
1.定位position+margin外边距(需要知道子盒子的宽高)
/*父盒子*/ position: relative; /*子盒子*/ position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px;
2.定位position+transform(不需要知道宽高)
/*父盒子*/ position: relative; /*子盒子*/ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
优点:1. 内容可变高度 2. 代码量少
缺点: 1. IE8不支持 2. 属性需要写浏览器厂商前缀 3. 可能干扰其他transform效果 4. 某些情形下会出现文本或元素边界渲染模糊的现象
3.使用弹性盒子flex布局(不需要知道宽高)
/*父盒子*/ display: flex; justify-content: center; align-items: center;
4.margin:auto(不需要知道宽高)
父盒子本身需要宽度;
设置margin自动适应,然后设置定位的上下左右都为0,就如四边均衡受力从而实现盒子的居中;
position: absolute;
left:0;
right:0;
top: 0;
bottom: 0;
margin: auto;
如果父子元素都有设置宽高:margin: 150px auto;
5.table-cell
将父盒子设置为table-cell(能够使元素呈单元格的样式显示),并设置text-align: center(使内容水平居中);vertical-align: middle(使内容垂直居中);。子盒子设置为inline-block可以使其内容变为文本格式,也可设置宽高;
.father{ display: table-cell; width: 400px; height: 400px; vertical-align: middle; text-align: center; } .child{ display: inline-block; vertical-align: middle; }