CSS-垂直置中的方法

整理常用CSS常用的 垂直置中 的方法。


文字的垂直置中方法

此方法適用 單行,因為是行高,所以會在行內元素的上下都加上行高的 1/2 ,
如果多行,第二行與第一行的間距會變超大,就會導致沒有垂直置中的效果。

1
2
3
4
5
6
7
8
9
// height 和 line-height 要一樣高

.div0,.div1 {
width: 300px;
+ height: 250px;
+ line-height: 250px;
text-align: center;
border: 1px solid #000;
}

See the Pen 垂直置中 - line-height by Kanboo (@Kanboo) on CodePen.


calc & transform

使用 calc 動態計算的能力,讓要置中的 div 的 top 屬性,
與上方的距離是「50% 的外框高度 + 50% 的 div 高度」,就可以做到垂直置中。

範例1:設定top:50%,再扣掉 div 的 高度/2

  • 方法1:top: calc( 50% - (高度/2) )
  • 方法2:top: 50%; margin-top: -(高度/2);
  • 方法3:top: 50%; transform: translateY(-50%); 自行計算50%的div高度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.redbox {
background: #c00;
float: left;
+ position: relative; //要宣告position,才能使用 top、left
width: 30px;
- //計算方法1
+ height: 30px;
+ top: calc(50% - 15px); //高:30/2=15
}
.greenbox {
background: #0c0;
float: left;
position: relative;
width: 30px;
- //計算方法2
+ height: 80px;
+ top: 50%;
+ margin-top: -40px; //高:80/2=40
}
.bluebox {
background: #00f;
float: left;
position: relative;
width: 30px;
height: 50px;
- //計算方法3
+ top:50%;
+ transform: translateY(-50%);
}

See the Pen 垂直置中 - calc 動態計算1 by Kanboo (@Kanboo) on CodePen.

範例2:將三個div設定寬高各30px,將滑鼠移到黑框內,可觀看效果。

See the Pen 垂直置中 - calc 動態計算2 by Kanboo (@Kanboo) on CodePen.


絕對定位

利用絕對位置來指定,要將 上下 的數值都設為 0,再搭配一個 margin:auto,就可以辦到垂直置中。

邏輯:
這個方法同時設定top和bottom為0,使得這個div完全不可能符合,最後再透過margin這個指令,讓它達到垂直置中的效果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  .redbox {
- // 垂直置中
background: #c00;
position: absolute; //要宣告,才能使用 top、left
+ top: 0;
+ bottom: 0;
+ margin: auto;
}
.bluebox {
- // 垂直置中 + 水平置中
background: blue;
position: absolute; //要宣告,才能使用 top、left
top: 0;
bottom: 0;
+ left: 0;
+ right: 0;
margin: auto;
}

See the Pen 垂直置中 - 絕對定位 by Kanboo (@Kanboo) on CodePen.


Flexbox

CSS3 最威的盒子模型:Flexbox,使用 align-itemsalign-content 的屬性,

輕輕鬆鬆就可以做到垂直置中的效果喔,Bootstrap 4 也有用喔。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.div0 {
+ display: flex;
+ align-items: center;
+ justify-content: center;
width: 150px;
height: 150px;
border: 1px solid #000;

.redbox {
width: 30px;
height: 30px;
background: #c00;
}
}

See the Pen 垂直置中 - Flexbox by Kanboo (@Kanboo) on CodePen.


參考文章