第一种方法
div.content{
/*让元素变成定位元素*/
position: absolute;
width: 300px;
height: 300px;
/*元素的margin值都设置为auto*/
margin: auto;
/*元素的定位距离上,下,左,右都为0*/
top:0;
left:0;
bottom: 0;
right: 0;
background: red;
}
/*兼容性好,但不支持IE7以下的浏览器*/
第二种方法:
div.content{
/*让元素变成定位元素*/
position: absolute;
width: 300px;
height: 300px;
/*元素的定位距离上,左都为50%*/
left:50%;
top:50%;
/*设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)*/
transform: translate(-50%,-50%);
}
/*CSS3样式,只支持IE9以上的浏览器*/
第三种方法:
div.content{
/*让元素变成定位元素*/
position: absolute;
width: 300px;
height: 300px;
/*元素的定位距离上,左都为50%*/
left:50%;
top:50%;
/*设置元素的左外边距、上外边距为宽高的负1/2*/
margin-left:-150px;
margin-top:-150px;
}
/*兼容性好;缺点:必须知道元素的宽高*/
第四种写法:
.box{
/*设置需要垂直水平居中的父元素为flex布局*/
display: flex;
width:300px;
height: 300px;
/*让包含的元素水平居中*/
justify-content: center;
/*让包含的元素垂直居中*/
align-items: center;
background: red;
}
.box .content{
background: yellow;
}
/*CSS3属性,兼容性不太好,IE10以上才能使用*/