作为一名程序媛
在编写页面的时候
经常还会遇到水平或者垂直居中的一些布局
今天正好有空
就把各种居中的方式都总结了一下
分享给大家
希望能给大家带来帮助
1.已知宽高背景图与背景图上的文字都水平垂直居中
.img-bg{ position: absolute; background: url("http://source.kakehotels.com/kake/frontend/img/flashsales-icon.png") no-repeat; width: 90px; height: 90px; background-size: 100%; top:0; bottom:0; left:0; right: 0; margin:auto; line-height: 90px; font-size: 12px; color: #fff;}
2.有宽度的div水平居中
.width-center{ width: 300px; text-align: center; margin: 0 auto; background:pink;}
3.有绝对定位的div水平居中
.position-center{ position: absolute; top:0; bottom: 0; width: 300px; height: 300px; margin: auto 0; background: pink; text-align: center;}
4.有绝对定位的div水平跟垂直都居中
.vertical-center-position{ position: absolute; width: 300px; height: 300px; background: #f5f5f5; text-align: center; top:0; bottom:0; left:0; right: 0; margin:auto;}
5.已知宽高的容器的水平垂直方向居中
.vertical-center-width{ width: 300px; height: 300px; position: absolute; background: #f5f5f5; text-align: center; top:50%; left: 50%; margin-top: -150px; margin-left: -150px;}
6.未知宽高的容器的水平垂直方向居中注:transform属性,低版本浏览器不兼容,例如IE8
.vertical-center-nowidth{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);}
7.水平垂直居中记得要想到flexbox此时.div无论是否已知宽高,都能两个方向居中
.container{ display: flex; align-items: center; justify-content: center;}.container div{ color: pink;}
8.手机端垂直居中弹框
<div class="popupBg"></div> <div class="popup"> <img src="images/fudai-dialog.png"/></div>.popupBg{position: fixed;top: 0;left: 0;right: 0;bottom: 0;background: rgba(0,0,0,.8);z-index: 100;}.popup{position: fixed;top: 50%;left: 50%;transform: translate(-50%,-50%);-webkit-transform: translate(-50%,-50%);z-index: 100;background: #FFF;}
http://www.weste.net/2014/12-...
以上就是8种常用的css水平垂直居中方法,大家可以在实际项目中加以运用,