通過relative定位
這種方法的思路是,使用relative將元素相對父元素下移50%,在通過transform使元素相對自身上移50%,這樣元素就處在父元素的正中間了,示意圖:
實例
<!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>
運行:
兼容性
同上