定位3种
- 第一种
.box{
box-sizing: border-box;
width: 50px;
left: 100px;
border: 1px solid #cccccc
background: blue;
}
body{
position:relative;
}
.box{
position:absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -50px;
}
问题:这种一定要知道具体的宽和高,自适应的盒子模型不适合使用
- 第二种
.box{
box-sizing: border-box;
width: 50px;
left: 100px;
border: 1px solid #cccccc
background: blue;
}
body{
position:relative;
}
.box{
position:absolute;
top: 0;
left: 0;
bottom:0;
right: 0;
margin:auto;
}
问题 : 这种方式必须得设置宽高
- 第三种 CSS3
.box{
box-sizing: border-box;
width: 50px;
left: 100px;
border: 1px solid #cccccc
background: blue;
}
body{
position:relative;
}
.box{
position:absolute;
top: 50%;
left: 50%;
transform:translation(-50%, -50%);
}
- 问题:兼容性不是很好
- CSS3中的flex布局
.box{
box-sizing: border-box;
width: 50px;
left: 100px;
border: 1px solid #cccccc
background: blue;
}
body{
display: flex;
justify-content: center;
align-items: center;
}
问题:兼容性不是很好
- display: table-cell
<div class="parent">
<div class="child">child</div>
</div>
.parent{
width:500px;
height:500px;
backgroud: green;
display:table-cell;
vertical-align: middle;
text-align: center;
}
.son{
display: inline-block
}
问题:这种方法是借用设置文本样式的方法,控制文本的水平和居中,父元素必须有固定的宽和高才行
- JS实现
<div class="box" id="box">box</div>
let html = document.documentElement,
box = document.getElementById(‘box‘),
winW = html.clientWidth,
winH = html.clientHeight,
boxW = box.offsetWidth,
boxH = box.offsetHeight;
html.style.position = "relative";
box.style.position = "absolute";
box.style.left = (winW - boxW) /2 + ‘px‘;
box.style.top = (winH - boxH) /2 + ‘px‘