题外话:这是一个让人抓狂的问题。
HTML文档结构如下:
<div class="outer">
<div class="inner"></div>
</div>
实现效果:
1.(子元素已知宽高)给父容器设置相对定位(relative),子元素设置为绝对定位(absolute),top、left设置为50%,margin-top、margin-left分别设置为高宽的一半的负数。
.outer{
position:relative;
width:80%;
height:400px;
background:#DCDCDC;
}
.inner{
width:400px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin-left:-200px; /*width一半的负数*/
margin-top:-100px; /*height一半的负数*/
background:green;
border:2px solid #000000;
}
2.(子元素未知宽高)使用CSS3新特性transform。设置父元素相对定位(relative),子元素绝对定位(absolute),top、left为50%,X轴、Y轴偏移-50%。
.outer{
position:relative;
width:80%;
height:400px;
background:#DCDCDC;
}
.inner{
width:30%;
height:40%;
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%); /*X负方向移宽度的一半,Y负方向移高度的一半*/
background:green;
border:2px solid #000000;
}
3.(子元素未知宽高)父元素相对定位(relative),子元素绝对定位(absolute),top/right/bottom/left均为0,margin为auto。
.outer{
position:relative;
width:80%;
height:400px;
background:#DCDCDC;
}
.inner{
width:30%;
height:40%;
position:absolute;
top:0;
right:0;
bottom:0;
left:0;
margin:auto;
background:green;
border:2px solid #000000;
}
4.(父元素已知宽高)父元素设置display为flex,项目在主轴上居中(justify-content),项目在交叉轴上居中(veritcal-items)。
.outer{
width:600px;
height:400px;
display:flex; /*指定容器为flex容器,若父元素为行内元素,则值为inline-flex*/
justify-content:center; /*主轴对齐方式*/
vertical-items:center; /*交叉轴对齐方式*/
background:#DCDCDC;
}
.inner{
width:30%;
height:40%;
background:green;
border:2px solid #000000;
}
附:
display属性值flex说明
5.CSS3新特性,calc()属性(注:目前浏览器对此属性的支持度不高,最好在写CSS的时候,兼容其它浏览器)
.outer{
width:600px;
height:400px;
position:relative;
background:#DCDCDC;
}
.inner{
position:absolute;
left:210px;
width:calc(100% - (210px + 2px) * 2);
top:120px;
height:calc(100% - (120px + 2px) * 2);
background:green;
border:2px solid #000000;
}