做爲一名程序媛
在編寫頁面的時候
常常還會遇到水平或者垂直居中的一些佈局
今天正好有空
就把各類居中的方式都總結了一下
分享給你們
但願能給你們帶來幫助css
1.已知寬高背景圖與背景圖上的文字都水平垂直居中html
.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水平居中web
.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水平跟垂直都居中frontend
.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屬性,低版本瀏覽器不兼容,例如IE8flex
.vertical-center-nowidth{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
7.水平垂直居中記得要想到flexbox此時.div不管是否已知寬高,都能兩個方向居中flexbox
.container{ display: flex; align-items: center; justify-content: center; } .container div{ color: pink; }
8.手機端垂直居中彈框url
<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水平垂直居中方法,你們能夠在實際項目中加以運用,spa