垂直居中實(shí)現(xiàn)方法
方法一
顯示設(shè)置父元素為:table,子元素為:cell-table弱恒,這樣就可以使用vertical-align: center纽绍,實(shí)現(xiàn)水平居中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知寬高元素水平垂直居中</title>
</head>
<style>
.parent1{
display: table;
height:300px;
width: 300px;
background-color: #FD0C70;
}
.parent1 .child{
display: table-cell;
vertical-align: middle;
text-align: center;
color: #fff;
font-size: 16px;
}
</style>
<body>
<div class="parent1">
<div class="child">hello world-1</div>
</div>
</body>
</html>
方法二
使用一個(gè)空標(biāo)簽span設(shè)置他的vertical-align基準(zhǔn)線為中間乡话,并且讓他為inline-block,寬度為0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知寬高元素水平垂直居中</title>
</head>
<style>
.parent2{
height:300px;
width: 300px;
text-align: center;
background: #FD0C70;
}
.parent2 span{
display: inline-block;;
width: 0;
height: 100%;
vertical-align: middle;
zoom: 1;/*BFC*/
*display: inline;
}
.parent2 .child{
display: inline-block;
color: #fff;
zoom: 1;/*BFC*/
*display: inline;
}
</style>
<body>
<div class="parent1">
<div class="child">hello world-1</div>
</div>
<div class="parent2">
<span></span>
<div class="child">hello world-2</div>
</div>
</body>
</html>
方法三
子元素絕對(duì)定位咳促,距離頂部 50%,左邊50%勘伺,然后使用css3 transform:translate(-50%; -50%)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知寬高元素水平垂直居中</title>
</head>
<style>
.parent3{
position: relative;
height:300px;
width: 300px;
background: #FD0C70;
}
.parent3 .child{
position: absolute;
top: 50%;
left: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent3">
<div class="child">hello world-3</div>
</div>
</body>
</html>
方法四
使用css3 flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知寬高元素水平垂直居中</title>
</head>
<style>
.parent4{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height:300px;
background: #FD0C70;
}
.parent4 .child{
color:#fff;
}
</style>
<body>div> <div class="parent4">
<div class="child">hello world-4</div>
</div>
</body>
</html>