- 定位:三种
- display:flex
- JavaScript
- display:table-cell
一、定位
第一种,元素需要有明确的宽高
<body>
<div class="box" id="box">
水平居中
</div>
</body>
css
html,
body{
position:relative;
height:100%;
overflow:hidden;
}
.box{
width:100px;
height:50px;
// 其他样式省略...
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-50px;
}
第二种,不需要考虑元素的宽高但是必须要有宽高
.box{
width:100px;
height:50px;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
第三种,不需要具体宽高,但是有兼容
.box{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
二、display:flex
移动端常用,有兼容
body{
display:flex;
justify-content;center;
aligin-items:center;
}
三、JavaScript
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';
html,
body{
position:relative;
height:100%;
overflow:hidden;
}
四、display:table-cell
项目中基本不用,给父级元素设置,且父级元素必须得有固定宽高,这个方法是控制文本水平垂直居中的
body{
display:table-cell;
vertical-align:middle;
text-align:center;
/* 固定宽高 */
width:800px;
height:800px;
}
.box{
display:inline-block;
}