一块茁、使用transform進(jìn)行居中
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進(jìn)行居中(利用margin負(fù)值進(jìn)行定位)
上下左右居中
.contain{
position: relative;
width: 100%;
height: 100vh;
}
.center-box{
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -250px;
/* 負(fù)數(shù)為盒子的一半 */
width: 500px;
height: 500px;
background-color: #FF0000;
}
三悲没、fixed用法同上(效果圖)