方法一、通过top和margin-top
<style>
.box {
width: 100%;
height: 500px;
background: red;
position: relative;
}
.content {
width: 200px;
height: 200px;
background: green;
margin: 0 auto; /*水平居中*/
position: absolute;
top: 50%;
margin-top: -100px;
left: 50%;
margin-left: -100px;
}
</style>
方法二、通过top和transform
<style>
.box {
width: 100%;
height: 500px;
background: red;
position: relative;
}
.content {
width: 200px;
height: 200px;
background: green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
or
<style>
.box {
width: 100%;
height: 500px;
background: red;
}
.content {
width: 200px;
height: 200px;
background: green;
position: relative;
top: 50%;
transform: translateY(-50%);
margin: 0 auto;
}
</style>
方法三、使用display、align-items和justify-content
<style>
.box {
width: 100%;
height: 500px;
background: red;
display: flex;
align-items: center;
justify-content: center;
}
.content {
width: 200px;
height: 200px;
background: green;
}
</style>
网友评论