1.绝对定位——margin:auto
原理:元素在过度受限情况下,将margin设置为auto,浏览器会重算margin的值,过度受限指的是同时设置top/bottom与height或者left/right与width。
.parent{position: relative;width: 500px;height: 500px;background-color: #ccc;}
.pos{position: absolute;background-color: #f0f;top: 0;bottom: 0;left: 0;right: 0;width: 200px;height: 200px;margin: auto;}
2.绝对定位——top:50%
.pos{position: absolute;background-color: #f0f;top: 50%;left: 0;right: 0;width: 200px;height: 200px;margin: auto;}
然后设置margin-top:-1/2自身高度的一半;已知高度时,如上,直接设置:margin-top:-100px;
或者用css3: {top:50%;left:50%;transform: translate(-50%,-50%);}宽高可以不设置,不设置的时候,宽度为parent的1/2
3.table布局
.parent{display:table;}
.pos{display:table-cell;vertical-align: middle;}
4.flex布局
.parent{display:flex;align-items: center;justify-content: center;}
5.单行文字
{height:30px;line-height:30px;}