盒子水平垂直居中的方法
(1)使用定位的方法(三种方法):
第一种方法:(已知盒子的宽高,需要计算盒子的宽高)
<body>
<div class="father">
<div class="son">儿子</div>
</div>
</body>
<style>
.father{
position: relative;
/* 这一步是为了让son基于father定位 */
width: 500px;
height:300px;
border: 1px solid blue;
}
.son{
position: absolute;
left: 50%;
top: 50%;
/* 到这一步为止,son的左上角是在father里面垂直居中的 */
margin-left: -100px;
margin-top: -50px;
/* 这里是为了让son的中心位置在father中垂直居中,所以取了son宽高的一半。 */
width: 200px;
height: 100px;
background-color: pink;
}
</style>
第二种方法:(盒子必须要有宽高,但是不需要计算宽高)
.son{
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 200px;
height: 100px;
background-color: pink;
}
第三种方法:(不需要知道盒子的宽高)
.son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: pink;
}
(2)使用display:flex的方法:
.father{
display: flex;
justify-content: center;
/* x轴 */
align-items: center;
/* y轴 */
width: 500px;
height:300px;
border: 1px solid blue;
}
.son{
width: 200px;
height: 100px;
background-color: pink;
}
(3)使用JavaScript的方法:
<body>
<div class="father" id="box">
js实现垂直居中
</div>
<script>
let HTML = document.documentElement;
windowW = HTML.clientWidth;
windowH = HTML.clientHeight;
boxW = box.offsetWidth;
boxH = box.offsetHeight;
console.log(boxH)
box.style.position = "absolute";
box.style.left = (windowW-boxW)/2+'px';
box.style.top = (windowH-boxH)/2+'px';
</script>
</body>
<style>
body{
position: relative;
}
#box {
width: 200px;
height: 100px;
background-color: pink ;
}</style>