css实现盒子的垂直居中显示

body内容区
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
方法一:利用定位(常用)
<style>
.parent {
position: relative;
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
background-color: skyblue;
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
</head>
方法二:利用margin:auto
<style>
.parent {
position: relative;
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
background-color: skyblue;
position: absolute;
margin:auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
方法三:利用display:table-cell
<style>
.parent {
width: 300px;
height: 300px;
border: 1px solid #000;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
background-color: skyblue;
display:inline-block;
}
</style>
方法四:利用flex布局(常用)
<style>
.parent {
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
background-color: skyblue;
}
</style>
方法五:利用transform
<style>
.parent {
width: 300px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 1px solid #999;
background-color: skyblue;
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%,-50%);
}
</style>