題目點評
這道題目的提問比較多,連續問了三個問題,正常元素、絕對定位元素、互動元素如何居中,並且居中沒有說清楚是垂直居中仍是水平居中,要回答清楚這個問題,必須得有深厚的功底,並且要分類的來回答,條理要清楚。能夠先把水平居中各類狀況說清楚,而後在把垂直居中說清楚。css
(一)元素水平居中的方式
1)行級元素水平居中對齊(父元素設置 text-align:center) html
- <div style="width: 200px; height: 100px;border: 1px solid;text-align:center;">
- <span>行級元素垂直居中</span>
- </div>
![](http://static.javashuo.com/static/loading.gif)
2) 塊級元素水平居中對齊(margin: 0 auto)ide
- <div style="width: 200px; height: 100px;border: 1px solid;text-align: center;">
- <div style="border: 1px solid red;margin: 0 auto;height: 50px;width: 80px;"> 塊級元素水平居中</div>
- </div>
3)浮動元素水平居中url
html代碼
- <div class="outerbox">
- <div class="innerbox">我是浮動的</div>
- </div>
CSS樣式spa
- .outerbox{
- float:left;
- position:relative;
- left:50%;
- }
- .innerbox{
- float:left;
- position:relative;
- right:50%;
- }
![](http://static.javashuo.com/static/loading.gif)
html代碼
- <div class="outerbox">
- <div>我是浮動的</div>
- </div>
css代碼.net
- .outerbox{
- background-color:pink; /*方便看效果 */
- width:500px ;
- height:300px; /*高度能夠不設*/
- margin: -150px 0 0 -250px; /*使用marin向左移動250px,保證元素居中*/
- position:relative; /*相對定位*/
- left:50%;
- top:50%;
- }
![](http://static.javashuo.com/static/loading.gif)
4)讓絕對定位的元素水平居中對齊code
這種方式很是獨特,你們必定要記牢這種方式,會用這種方式的薪資待遇必然高出幾千¥orm
- .center{
- position: absolute; /*絕對定位*/
- width: 500px;
- height:300px;
- background: red;
- margin: 0 auto; /*水平居中*/
- left: 0; /*此處不能省略,且爲0*/
- right: 0; /*此處不能省略,且爲0*/
- }
經驗分享:水平居中的主要屬性有
1. text-alin:center;視頻
2. margin:0 autohtm
3. position:relative|absolute; left:50%;
(二)元素垂直居中對齊
1)對行級元素垂直居中(heiht與line-height的值同樣)
- height:300px;
- line-height:300px;
![](http://static.javashuo.com/static/loading.gif)
2)對
塊級元素垂直居中對齊
2.1 父元素高度固定的狀況
1)父元素的height與line-height值相同
2)須要垂直居中的元素
vertical-align:middle;// 垂直居中對齊
display:inline|inline-block 塊級元素轉行級元素
HTML代碼
- <div class="center">
- <div class="inner"></div>
- </div>
CSS代碼
- .center{
- width: 500px;
- height:300px;
- line-height: 300px;
- border:1px solid;
- }
- .inner{
- background: blue;
- width: 300px;
- height: 100px;
- display: inline-block;
- vertical-align: middle;
- }
2.2 父元素高度不固定的狀況
父元素的padding-top和padding-bottom同樣
--------------------------------------------------------------------------------------------------------------------
若是看不懂,能夠看視頻操做,代碼演示 http://www.chuanke.com/3885380-190205.html