標籤:

你能夠想到多少種讓元素居中的方法?

行內元素水平居中

給其父元素設置text-align: center即可

.box { text-align: center;}

塊級元素水平居中

給元素本身添加margin-left: auto; margin-right: auto;

.box { width: 600px; margin-left: auto; margin-right: auto;}

padding垂直居中

在容器高度不固定的情況下,給內容設置相同的上下padding,使內容撐開父容器,達到視覺上垂直居中的效果。

line-height垂直居中

一般來說,給父容器添加line-height屬性等於其高度,可實現父容器中的文字垂直居中。

絕對定位居中

.box-parent { width: 600px; height: 600px; background-color: black; position: relative;}.box { width: 300px; height: 300px; position: absolute; top: 50%; left: 50%; margin-top: -150px; margin-left: -150px;}<div class="box-parent"> <div class="box"></div></div>

因為給left和right屬性設置百分比值時是相對父容器的長度,所以當設置了 left: 50%; right:50%;之後,元素的左上角會在父容器的中心。此時如果想要使元素整體位於父容器的中心,需要使元素在其原始位置向左和上移動本身長度和高度的一半。

/*上述便是為何要加下面兩句負margin的理由*/margin-top: -150px;margin-left: -150px;/*亦或是採用如下寫法,效果相同*/top: calc(50% - 150px);left: calc(50% - 150px);

寬高的不固定的情況

上述情況用於元素自身寬高是固定的情況,當寬高不固定時,我們就無從知曉元素該偏移多少距離。

此時可以使用下面的寫法:

.box { width: 300px; height: 300px; position: absolute; top: 50%; left:50%; transform: translate(-50%,-50%);}

MDN上對於transform的描述:

CSS **transform **屬性允許你修改CSS視覺格式模型的坐標空間。使用它,元素可以被轉換(translate)、旋轉(rotate)、縮放(scale)、傾斜(skew)。

/*第一個參數表示x軸移動距離,第二個參數代表y軸移動距離*/transform: translate(20px, 20px);transform: translate(10%, 10%); /*當採用百分比寫法時,移動距離是相對自身的寬高,例如此處是本身寬高的10%*/

注意點:transform屬性只對塊級元素生效。

vertical-align: middle;垂直居中

<style> * { margin: 0; padding: 0; } .box { width: 500px; height: 300px; outline: 1px solid red; margin: 10px auto; } .box h1 { vertical-align: middle; display: inline-block; } .box::before { content: "1"; height: 100%; display: inline-block; background-color: pink; vertical-align: middle; } </style></head><body> <div class="box"> <h1>用於垂直居中顯示的文本</h1> </div></body>

核心就是使用vertical-align: middle;

用父元素 baseline 高度加上父元素中 x-height 的一半的高度來對齊當前元素的垂直方向的中點。

baseline 所處的高度跟字體有關,x-height 的高度也跟字體有關...(略)

為什麼此處一定要有偽元素呢?單純給h1設置vertical-align: middle;為什麼視覺上沒有生效?

我的個人理解是,如果沒有偽元素,父元素div中還有大量空白(空行),當時用vertical-align: middle;對齊時,baseline並不是div唯一的。

所以此處給添加高度為100%的偽元素後,整個div只有一行(一個line-box),自然可以對齊。

( 如有錯誤,還望指出:) )

flex布局居中

.flex-box { width: 100vw; height: 100vh; display: flex; align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中 */}

table-cell居中

<style> .box { width: 300px; height: 300px; border: 1px solid; display: table-cell; vertical-align: middle; text-align: center; }</style><body> <div class="box"> 用於居中的文本 </div></body>

其他方法待作者學習補充...

推薦閱讀:

JS入門-1.關於 if(xx)與 a == b 的判斷
免費直播 | 2018,你最需要的前端學習指南&求職指南!飢人谷
可能是最全的 Node.js 9 新特性整理
十年web前端開發工程師告訴你怎樣零基礎入門

TAG:前端入門 |