文章目錄
- 通過relative定位
-
- 執行個體
- 相容性
- 通過absolute定位
-
- 執行個體
- 相容性
- 通過flex布局(1)
-
- 執行個體
- 相容性
- 通過flex布局(2)
-
- 執行個體
- 相容性
通過relative定位
這種方法的思路是,使用relative将元素相對父元素下移50%,在通過transform使元素相對自身上移50%,這樣元素就處在父元素的正中間了,示意圖:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuMjN2ATNyETMyIzMwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
執行個體
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>change-to-flex</title>
<style>
body {
margin: 0;
}
.border {
height: 100px;
width: 100px;
border: 2px solid blue;
display: inline-block;
}
.item {
width: 40px;
height: 40px;
background-color: red;
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="border">
<div class=item></div>
</div>
</body>
</html>
運作:
注意:
- 通過這種方式垂直居中,父元素的高度必須是确定的,因為top:50%是通過父元素的高度計算的(如果left:50%就不會要求父元素的寬度确定,查資料說因為block的元素的寬預設是父元素的100%)
- 還有一個容易被忽視的就是:父元素的display不能是
、
table
、
contents
inline
相容性
這種方式需要用到css3的transform 2d轉換,相容性見下圖:
通過absolute定位
通過absolute的思路是,将要垂直居中的元素的position設定為absolute,然後将它的top和bottom均設定為0,再設定它的margin-top和margin-bottom為auto,則它會上下垂直居中,我們通常用這個思路來實作水準居中,其實它也是可以實作垂直居中的
執行個體
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>change-to-flex</title>
<style>
body {
margin: 0;
}
.border {
width: 100px;
height: 100px;
border: 2px solid blue;
position: relative
}
.item {
width: 40px;
height: 40px;
background-color: red;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}
</style>
</head>
<body>
<div class="border">
<div class=item></div>
</div>
</body>
</html>
運作:
相容性
position是css很早就有的一個屬性,相容性無疑是十分好的(position為sticky的相容性不是十分好)
注意:
- 注意要将需要垂直的居中元素的父元素的position設定為relative,使得abolute的相對對象為父元素
通過flex布局(1)
思路很簡單,通過flex布局的特性配合margin實作
執行個體
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>change-to-flex</title>
<style>
body {
margin: 0;
}
.border {
width: 100px;
height: 100px;
border: 2px solid blue;
display: flex;
}
.item {
width: 40px;
height: 40px;
background-color: red;
margin: auto 0;
}
</style>
</head>
<body>
<div class="border">
<div class=item></div>
</div>
</body>
</html>
運作:
相容性
使用flex布局,需要考慮到flex的相容性問題:
通過flex布局(2)
這種方式也是利用flex布局,不同上面的是,它配合flex自帶的交叉軸居中屬性
align-items: center
來實作垂直居中
執行個體
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>change-to-flex</title>
<style>
body {
margin: 0;
}
.border {
width: 100px;
height: 100px;
border: 2px solid blue;
display: flex;
align-items: center;
}
.item {
width: 40px;
height: 40px;
background-color: red;
}
</style>
</head>
<body>
<div class="border">
<div class=item></div>
</div>
</body>
</html>
運作:
相容性
同上