1.使用table-cell+vertical-align
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
width:500px;
height: 400px;
background-color: greenyellow;
display:table-cell;
vertical-align: middle;
}
.child{
width:300px;
height:200px;
background-color:red;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Demo</div>
</div>
</body>
</html>
原理:通过将父框转化为一个表格单元格显示(类似<td><tr>),再通过设置属性,使表格单元格内容垂直居中以达到垂直居中。
优点:兼容性好,ie8以上均支持
2.使用absolute+transform
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
position:relative;
width:200px;
height:100px;
background-color:green;
}
.child{
width:50%;
height:50%;
background-color:red;
position:absolute;
top:50%;
transform:translateY(-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">DEMO</div>
</div>
</body>
</html>
原理:类似于水平居中时的absolute+transform原理;
3.使用flex+align-items
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
width:300px;
height:200px;
background-color: green;
display:flex;
align-items:center;
}
.child{
width:50%;
height:50%;
background-color:red;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">Demo</div>
</div>
</body>
</html>
4.使用flex+flex-direction+justify-content
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
width:300px;
height:200px;
background-color:green;
display: flex;
flex-direction: column;
justify-content: center;
}
.child{
width:50%;
height:50%;
background-color:red;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">DEMO</div>
</div>
</body>
</html>
5.使用absolute+margin负边距
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
width:300px;
height:200px;
background-color:green;
position:relative;
}
.child{
width:50%;
height:50%;
background-color:red;
position:absolute;
top:50%;
margin-top:-50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">DEMO</div>
</div>
</body>
</html>
缺点:需知道子元素宽,高;以及高的一半;
6.使用absolute+margin
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
width:300px;
height:200px;
background-color:green;
position:relative;
}
.child{
width:50%;
height:50%;
background-color:red;
position:absolute;
top:0;
bottom:0;
margin:auto;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">DEMO</div>
</div>
</body>
</html>
7.使用padding
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.parent{
width:100%;
padding:100px 0;
}
.child{
width:50%;
height:100px;
background-color:red;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">DEMO</div>
</div>
</body>
</html>
网友评论