1、原理:要让div等块级元素水平和垂直居中,必需知道该div等块级元素的宽度和高度,然后设置位置为绝对位置,距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指页面窗口的宽度和高度的50%,最后将该div等块级元素分别左移和上移,左移和上移的大小就是该div等块级元素宽度和高度的一半。
.div1{
position: absolute;
left:50%;
top:50%;
margin-left: -150px;
margin-top: -150px;
width:300px;
height: 300px;
background: red;
}
2、利用CSS的margin设置为auto让浏览器自己帮我们水平和垂直居中。
.div1{
position: absolute;
left: 0px;
right: 0;
top:0;
bottom: 0;
margin: auto;
width:300px;
height: 300px;
background: red;
}