话不多说,一些你意想不到的方式实现垂直居中
几种方式实现垂直居中
如果 .parent 的 height 不写,你只需要 padding: 10px 0; 就能将 .child 垂直居中;
如果 .parent 的 height 写死了,就很难把 .child 居中,以下是垂直居中的方法。
- 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>
- 100% 高度的 afrer before 加上 inline block
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Christina DIY </title>
</head>
<body>
<div class="parent">
<span class=before></span><div class="child">
哈哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈--哈哈哈哈哈哈哈哈哈哈
</div><span class=after></span>
</div>
</body>
</html>
.parent{
border: 3px solid red;
height: 600px;
text-align: center;
}
.child{
border: 3px solid black;
display: inline-block;
width: 300px;
vertical-align: middle;
}
.parent .before{
outline: 3px solid red;
display: inline-block;
height: 100%;
vertical-align: middle;
}
.parent .after{
outline: 3px solid red;
display: inline-block;
height: 100%;
vertical-align: middle;
}
- margin-top -50px
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CT</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;
width: 300px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
height: 100px;
margin-top: -50px;
}
- translate -50%
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CT</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%);
}
- absolute margin auto
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CT</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;
width: 300px;
height: 200px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
- flex
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CT</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;
}