一、使用transform进行居中
html部分
<div class="contain">
<div class="center-box"></div>
</div>
上下左右居中
.contain{
position: relative;
width: 100%;
height: 100vh;
}
.center-box{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 500px;
height: 500px;
background-color: #FF0000;
}
左右居中
.contain{
position: relative;
width: 100%;
height: 100vh;
}
.center-box{
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, 0);
width: 500px;
height: 500px;
background-color: #FF0000;
}
上下居中
.contain{
position: relative;
width: 100%;
height: 100vh;
}
.center-box{
position: absolute;
top: 50%;
left: 0;
transform: translate(0, 50%);
width: 500px;
height: 500px;
background-color: #FF0000;
}
二、使用margin进行居中(利用margin负值进行定位)
上下左右居中
.contain{
position: relative;
width: 100%;
height: 100vh;
}
.center-box{
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -250px;
/* 负数为盒子的一半 */
width: 500px;
height: 500px;
background-color: #FF0000;
}
三、fixed用法同上(效果图)

居中.png
网友评论