- table-cell
<div id="wrapper">
<div id="cell">
<div class="content">Content goes here</div>
</div>
</div>
#wrapper {
display: table;
}
#cell {
display: table-cell;
vertical-align: middle;
}
或者
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#wrapper {
/* display: table; */
background: aqua;
}
#cell {
display: table-cell;
min-height: 500px;
vertical-align: middle;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="cell">
<div class="content">Content goes here</div>
</div>
</div>
</body>
</html>
2 position absolute
下面這種必須固定高度
div class="content"> Content goes here</div>
#content {
position: absolute;
top: 50%;
height: 240px;
margin-top: -120px; /* negative half of the height */
}
優(yōu)點:
適用于所有瀏覽器
不需要嵌套標(biāo)簽
缺點:
沒有足夠空間時邪铲,content 會消失(類似div 在 body 內(nèi)疲憋,當(dāng)用戶縮小瀏覽器窗口,滾動條不出現(xiàn)的情況)
或者使用tansform好點渺尘,無需計算高度
#content {
position: absolute;
top: 50%;
height: 240px;
transfrom: translateY(-50%); // 本質(zhì)
}
position:absolute
必須固定寬高挫鸽,垂直水平居中
<div id="content"> Content here</div>
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 240px;
width: 70%;
}
flex
<div class="content">
<div class="item"></div>
</div>
.content {
display: flex;
align-teim: center;
}
文本垂直居中
<div class="content">
<div class="item"></div>
</div>
.content {
height:
}