margin-top -50%
// html 代码
<div class="parent">
<div class="child">
</div>
</div>
// css 代码
<style>
.parent{
height: 300px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
width: 300px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -50px;
}
</style>
translate -50%
// html 代码
<div class="parent">
<div class="child">
test
</div>
</div>
// css 代码
<style>
.parent{
height: 300px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
width: 300px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -150px;
margin-top: -50px;
}
</style>
absolute margin auto
// HTML 代码
<div class="parent">
<div class="child">
</div>
</div>
// CSS 代码
<style>
.parent{
height: 300px;
border: 1px solid red;
position: relative;
}
.child{
border: 1px solid green;
position: absolute;
width: 100px;
height: 100px;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
flex
// HTML 代码
<div class="parent">
<div class="child">
</div>
</div>
// CSS 代码
<style>
.parent{
height: 300px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child{
width: 100px;
height: 100px;
border: 1px solid green;
width: 300px;
}
</style>