1、居于position定位
(1)
body {
position: relative;
height: 100vh;
width: 100%;
}
.box-child {
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
备注:在这个方法中,box-child不用计算高度,但是必须有高度
(2)
body {
position: relative;
height: 100vh;
width: 100%;
}
.box-child {
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
备注:.box-child必须有宽高
(3)
body {
position: relative;
height: 100vh;
width: 100%;
}
.box-child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
备注:不必管宽高,但是不兼容
(4)
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.box-child {
}
备注:此方法有兼容问题,主要使用flex布局
(5)利用js
<div class="box-child" id="box">544444444444</div>
<script>
let html = document.documentElement;
let x = html.clientWidth;
let y = html.clientHeight;
let box = window.document.getElementById('box');
let boxH = box.offsetHeight;
let boxW = box.offsetWidth;
box.style.position = "absolute";
box.style.left = (x - boxW) / 2 + "px";
box.style.top = (x - boxH) / 2 + "px";
</script>
(6)
.box {
width: 400px;
height: 500px;
display:table-cell;
vertical-align: middle;
text-align: center;
background: red;
}
.box-child{
display: inline-block;
background: yellow;
}
备注:这种方法不常用,其中.box必须给定宽高