div垂直居中方法整理

水平居中很簡單塊級元素:margin:0 auto;內聯元素(行內元素): text-align:center,但是垂直居中的辦法相對來說麻煩點而且有很多不同的實現方法,今天做一個垂直居中的方法整理。
在這裏插入圖片描述

結構:

<div class="box">
		<div class="redbox"></div>
</div>

第一種:

.redbox{background-color: red;width: 50px;height:50px;display: inline-block;vertical-align: middle;margin: 0 auto;}
.box{border: saddlebrown 1px solid;width: 500px;height: 300px;margin: 0 auto;text-align: center;}
.box:before{content: "";display: inline-block;width: 0px;height: 100%;position: relative;vertical-align:middle;background-color: #8B4513;}

這辦法是需要改div的display,再用父元素創建一個僞div 高度設置爲100%,再利用vertical-align 屬性,該屬性定義行內元素的基線相對於該元素所在行的基線的垂直對齊。

描述
top 把元素的頂端與行中最高元素的頂端對齊
bottom 把元素的頂端與行中最低的元素的頂端對齊。
middle 把此元素放置在父元素的中部。

個人習慣寫css不喜歡展開,因爲覺得太佔行了,如果不太明白試着改一下僞類的高度就明白了。以最高的行內元素爲準:
在這裏插入圖片描述
第二種:

.box{border: saddlebrown 1px solid;width: 500px;height: 300px;margin: 0 auto;}
.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;position: relative;top: calc(50% - 25px);}

calc()函數用於動態計算長度值

水平居中後,用calc算top值,就是50%-自身的一半,這種方式有很多種實現的辦法,例如:

.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;position:relative;top: 50%;margin-top: -25px;}

不用動態計算,自己再寫一個margin-top頂上去就好

.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;position:relative;top: 50%;transform: translateY(-50%);}

這裏要注意translateY(-50%)是自身的50%,也就是-25px

第三種:

.box{border: saddlebrown 1px solid;display: table-cell;width: 500px;height: 300px;margin: 0 auto;vertical-align: middle;}
.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;}

改變父元素display以表單單元格形式顯示,再加個vertical-align: middle,最後也需要子元素水平居中。

第四種:

.box{border: saddlebrown 1px solid;display: flex;align-items: center;width: 500px;height: 300px;margin: 0 auto;}
.redbox{background-color: red;width: 50px;height:50px;margin: 0 auto;}

彈性盒子佈局,居中顯示

不依靠父元素垂直居中,例如:

比較適合做懸浮窗什麼的,如果是提示框就換成文檔定位
第一種:

.box{width: 100px;height:100px;background-color: aqua;position: absolute;left: 0px;right: 0px;bottom:0px;top: 0px;margin:auto;} 

第二種

.box{width: 100px;height:100px;background-color: aqua;position: absolute;top:calc(50% - 50px);left:calc(50% - 50px);}

也是根據這個有很多種算top和left的值,例:

.box{width: 100px;height:100px;background-color: aqua;position: absolute;top:50%;left:50%;transform: translateX(-50%) translateY(-50%);}
.box{width: 100px;height:100px;background-color: aqua;position: absolute;top:50%;left:50%;margin-left: -50px;margin-top: -50px;}

上面所說的只要沒有改父元素的display屬性都可以不依靠父元素達到垂直居中的目的。
以上理解若有錯幫忙指出,感謝!
在這裏插入圖片描述

發佈了32 篇原創文章 · 獲贊 46 · 訪問量 7229
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章