我们需要的效果就是在页面的视口上,居中显示出一个div用以承载信息
效果如下
第一种情况:确定宽高
此时我们只需要将该div设置为固定定位,最后设置top、left属性值即可
//css部分
body{
margin: 0;
background-color: khaki;
}
div{
width: 200px;
height: 200px;
background-color: #008c8c;
position: fixed;
top: calc(50% - 100px);
left: calc(50% - 100px);
}
上面是通过calc函数直接设置的top和left值,也可以直接设置为50%,再设置div的margin来实现同样的效果
body{
margin: 0;
background-color: khaki;
}
div{
width: 200px;
height: 200px;
background-color: #008c8c;
position: fixed;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
此时效果一致,达到了div页面居中显示。
第二种情况:不确定宽高
宽高不确定时,显然不能向上面那样设置margin的值了,但是我们可以使用margin:auto来实现同样的效果
body{
margin: 0;
background-color: khaki;
}
div{
width: 200px;
height: 200px;
background-color: #008c8c;
position: fixed;
top: 0;
left: 0;
buttom:0;
right:0;
margin:auto; //这里通过margin吸收掉外边距
}
这样通过margin:auto吸收掉外边距,达到DIV居中的显示方式
除此之外,还可以使用ttransforms属性的translate设置DIV的偏移量来实现
body{
margin: 0;
background-color: khaki;
}
div{
width: 200px;
height: 200px;
background-color: #008c8c;
position: fixed;
top: 50%;
left: 50%;
transform:translate(-50%,-50%); //DIV分别沿X、Y轴偏移50%自身宽高的长度的距离
}
同样可以达到我们需要的效果,但是这种写法存在兼容性问题,使用时要慎重。
如果书写存在错误或者漏洞欢迎大家指出或者补充,大家一起交流学习