盒子水平垂直居中的方法
(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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/280373.html
標籤:其他
上一篇:CSS相應式卡包
