水平垂直居中 5种方式
absolute三种:
margin-top:-50px;
transform:translate(-50%,-50%);
left:0, right:0, top:0, bottom:0,margin:auto;
flex一种: display:flex; justify-content:center;align-items:center;
js一种
<html>
<style>
html,body{
height:100%;
overflow:hidden;
}
.box{
width:100px;
height:50px;
border:1px solid blue;
}
body{
position:relative;
}
/*水平垂直居中 5种方式
absolute三种:margin-top:-50px;
transform:translate(-50%,-50%);
left:0, right:0, top:o, bottom:0,margin:auto;
flex一种: display:flex;
justify-content:center;
align-items:center;
js一种
*/
/* 定位1 知道具体宽高的情况*/
.box{
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-50px;
}
/* 2.有宽高 不需要知道宽高是多少 */
.box{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
/*3. 不需要具体宽高 缺点兼容性不好*/
.box{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
/*4. flex方式 移动端用得多 缺点兼容性不好*/
body{
display:flex;
justify-content:center;
align-items:center;
}
/*5. table-cell方式 要求父级body有固定宽高 项目中很少用*/
/*body{
display:table-cell;
vertical-align:middle;
text-align:center;
width:500px;
height:500px;
background-color: yellow
}
.box{
display:inline-box;
}*/
</style>
<body>
<div class="box" id="box">
<p>hh</p>
</div>
</body>
</html>
<script>
//js实现垂直居中
let HTML = document.documentElement,
winW = HTML.clientWidth,
winH = HTML.clientHeight,
boxW = box.offsetWidth,
boxH = box.offsetHeight;
box.style.position = "absolute"
box.style.left = (winW-boxW)/2 + 'px';
box.style.top = (winH-boxH)/2 + 'px';
</script>