css各种水平垂直居中,网上查了一下,总结以下几种
line-height垂直居中
缺点,仅限于单行文字
- .item{
- text-align: center;
- height: 100px;
- line-height: 100px;
- }
水平垂直居中
padding垂直居中
缺点,内容不确定时,高度不好固定
- .item{
- padding: 40px 0;
- }
水平
垂直居中
垂直居中
margin垂直居中
需要知道父层和子层高度,然后marginLeft && marginTop = 父层/2 – 子层/2;
缺点,不灵活
- .wrap{
- height: 100px;
- width: 220px;
- }
- .item{
- width: 100px;
- height: 30px;
- margin-top: 35px;
- margin-left: 60px;
- }
水平垂直居中
position垂直居中
需要知道子层高度,根据子层高度来设置margin;
缺点,不灵活
- .wrap{
- position: relative;
- width:220px;
- height: 200px;
- }
- .item{
- position: absolute;
- width: 100px;
- height: 50px;
- left: 50%;
- top: 50%;
- margin-left: –50px;
- margin-top: –25px;
- }
水平垂直居中
position垂直居中二
内容div固定宽高,不固定宽高都可以,但是父层貌似必须有宽高。
缺点:父层宽高,比较灵活
- .wrap{
- position: relative;
- width:220px;
- height: 200px;
- }
- .item{
- width: 100px;height: 50px;
- margin:auto;
- position: absolute;
- left: 0px;
- top: 0px;
- right:0px;
- bottom: 0px;
- }
固定高度
不固定高度
css3的calc垂直居中
也是需要知道父层宽高和自身宽高;
缺点,不灵活,兼容性
- .wrap{
- width:220px;
- height: 150px;
- overflow: hidden;
- }
- .item{
- width: 100px;
- height: 40px;
- margin:0 auto;
- margin-top: calc(150px/2 – 40px/2);
- }
垂直居中
css3的translate垂直居中
这个是最方便,尤其在移动端,简直神器!
- .wrap{
- width:220px;
- height: 150px;
- overflow: hidden;
- }
- .item{
- width: 100px;
- height: 40px;
- margin:0 auto;
- position: relative;
- top: 50%;
- transform:translate3d(0px,-50%,0px);
- }
垂直居中
text-align + vertical-align垂直居中
添加一个占位标签。
没啥大缺点,多加了一个标签
- .wrap{
- height: 150px;
- width:220px;
- }
- .placeholder{
- overflow: hidden;
- width: 0;
- min-height: inherit;
- height: inherit;
- vertical-align: middle;
- display: inline–block;
- }
- .item{
- width: 100px;
- height: 50px;
- vertical-align: middle;
- display: inline–block;
- }
垂直居中
text-align + line-height垂直居中
缺点:父元素必须有个行高。
- .wrap{
- line-height: 200px;
- }
- .item{
- line-height: normal;
- vertical-align: middle;
- display: inline–block;
- }
垂直居中
flex垂直居中。
唯一缺点就是兼容性了
- .wrap{
- display: -webkit-box;
- display: -moz-box;
- display: -ms-flexbox;
- display: -webkit-flex;
- display: flex;
- height: 150px;
- }
- .item{
- margin:auto; //这句话是关键
- width: 100px;
- height: 50px;
- }
垂直居中
flex垂直居中二
唯一缺点就是兼容性
- .wrap{
- display: -webkit-box;
- display: -moz-box;
- display: -ms-flexbox;
- display: -webkit-flex;
- display: flex;
- height: 150px;
- align-items: center ;
- justify–content: center;
- }
- .item{
- width: 100px;
- height: 50px;
- background: #555;
- line-height: 50px;
- }
垂直居中
table垂直居中
利用table表格的属性,来居中元素
- .wrap{
- display: table-cell;
- vertical-align: middle;
- text-align: center;
- height: 150px;
- }
- .item{
- width: 100px;
- line-height: 50px;
- display: inline–block; //转换为内联元素
- }
垂直居中
使用button标签
- .wrap{
- height: 150px;
- background: #222;
- border-radius: 0px;
- border:none;
- display:block;
- margin:20px auto;
- width: 220px;
- }
- .item{
- width: 100px;
- line-height: 50px;
- display: inline–block;
- }
垂直居中
😮 😮 😮 😮 😮 😮 😮 ………..太棒了
😮 好多种
牛人啊