如果父元素的height
不写,只需要设置父元素padding:10px 0;
就可以将子元素垂直居中; 如果父元素的height
写死了,就比较难垂直居中,以下是垂直居中的几种方法。
1.使用table
自带的功能实现垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<table class="parent">
<tr>
<td class="child">
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
</td>
</tr>
</table>
</body>
</html>
.parent{
border: 1px solid red;
height: 600px;
}
.child{
border: 1px solid green;
}
2.把div
装成table
实现垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="table">
<div class="td">
<div class="child">
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
</div>
</div>
</div>
</body>
</html>
div.table{
display: table;
border: 1px solid red;
height: 600px;
}
div.td{
display: table-cell;
border: 1px solid blue;
vertical-align: middle;
}
.child{
border: 1px solid black;
}
使用
display:table
把第一个div
转成table
,使用display:table-cell
把第二个div
转成tr
,利用table
自带的功能实现垂直居中。
3.使用绝对定位+transform: translate(-50%,-50%);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="parent">
<div class="child">
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
</div>
</div>
</body>
</html>
.parent{
height: 600px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
父元素使用相对定位,子元素使用绝对定位,设置子元素
top: 50%;left: 50%;transform: translate(-50%,-50%);
,完成相对父元素水平垂直居中
4.使用flex
布局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div class="parent">
<div class="child">
一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字一串文字
</div>
</div>
</body>
</html>
.parent{
height: 600px;
border: 3px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
border: 3px solid green;
width: 300px;
}
flex是最好用的,在父元素中设置
justify-content: center;align-items: center;
,就完成了子元素的水平和垂直居中