固定高寬div垂直居中
position: absolute; left: 50%; top: 50%; width:200px; height:100px; margin-left:-100px; margin-top:-50px;
不固定高寬div垂直居中的方法
方法一:
用一個“ghost”僞元素(看不見的僞元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是這個方法要求待居中的元素是 inline-block,不是一個真正通用的方案。
html如下:
<div class="block" style="height: 300px;"> <div class="centered"> <h1>haorooms案例題目</h1> <p>haorooms案例內容,案例內容haorooms案例內容</p> </div></div>
css如下:
.block {text-align: center;} .block:before { content: ''; display: inline-block; height: 100%; vertical-align: middle;margin-right: -0.25em} .centered {display: inline-block;vertical-align: middle; width: 50%;}
方法二:
可以用table佈局方法,但是這種方法也有侷限性!
寫法如下:
<table style="width: 100%;"> <tr> <td style="text-align: center; vertical-align: middle;"> Unknown stuff to be centered. </td> </tr></table>
由於table寫法比較費時,你也可以用div代替table,寫法如下:
html:
<div class="something-semantic"> <div class="something-else-semantic"> Unknown stuff to be centered. </div> </div>
css:
.something-semantic { display: table; width: 100%;} .something-else-semantic { display: table-cell; text-align: center; vertical-align: middle;}
css3不定寬高水平垂直居中
justify-content:center;//子元素水平居中 align-items:center;//子元素垂直居中 display:-webkit-flex;
運用margin:auto進行垂直居中
margin的值設置爲auto,可以讓我們對剩餘空間進行分配!我們知道,塊級元素設置爲margin:0 auto;可以左右居中顯示!那有沒有辦法讓margin設置爲margin:auto之後,上下左右都居中呢?上下左右都居中,就可以實現我們的垂直居中了!
答案是有的,只要我們讓上下有足夠的空間,就可以讓margin的auto來分配上下空間。
我們可以利用定位的方式,讓margin上下左右都有足夠的空間!那麼就可以用margin:auto來實現垂直居中了!
實現html如下:(做一個簡單的垂直彈框)
<div class="father"> <div class="son"></div> </div>
css代碼如下,很簡單,兼容性也蠻好,支持IE8+
.father{position:fixed;width:100%;height:100%;top;0;left:0;background-color:rgba(0,0,0,.7);}.son{position: absolute;top:0;left:0;bottom:0;right:0;width:50%;height:50%;margin:auto;background-color:red;}