首先需要说明,根据标准盒模型(这里暂且不关注低版本IE的盒模型),我们在css中设置的width指的是content-width,padding,margin,top,
left这些属性为百分数时,计算的依据为父元素的content-width+left-padding+right-padding
1.父div和子div都有固定宽高
情景如下:div#content在div#wrap中垂直居中
<body>
<div id="wrap">
<div id="content"></div>
</div>
</body>
<style type = "text/css">
#wrap {
width: 500px;
height: 500px;
border: 1px solid #ccc;
/*添加其他padding、margin都不会对下面的方法有影响*/
}
#content {
width: 300px;
height: 300px;
background-color: red;
}
</style
方法一,flex布局
#wrap {
display: flex;
justify-content: center;
align-items: center;
}
方法二,transform+absolute
#wrap {
position: relative;/*如果需要可以设置为obsolute,fixed,*/
}
#content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);/*此处不讨论兼容性*/
}
方法三,纯absolute
#wrap {
position: relative;/*如果需要可以设置为obsolute,fixed,*/
}
#content {
position: absolute;
top: 50%;
left: 50%;
margin-left:-150px;
margin-top: -150px;/*与方法二的差异在于没有使用css3的transform,不可设置为-50%,因为margin是以父元素宽度为基础计算的,设置为-50%后又回到左上角*/
}
方法四,margin:auto+absolute
#wrap {
position: relative;/*如果需要可以设置为obsolute,fixed,*/
}
#content {
position: absolute;
top: 0;
left: 0;
right:0;
bottom:0;
margin:auto
}
方法五,cacl计算
#wrap {
position: relative;/*如果需要可以设置为obsolute,fixed,*/
}
#content {
position: absolute;
top: calc(250px - 150px);/*不可用百分数,因为是以父元素宽度为基准的,所以用百分数达不到效果*/
left: calc(250px - 150px);
}
方法六,table-cell
这种方法需要在div#wrap和div#content之间添加一层包裹div#table-div,包裹住div#content
#wrap {
display: table;
}
#table-div {
display: table-cell;
vertical-align: middle;
text-align: center;
}
#content {
display: inline-block;
}
②父div有固定高度,子div没有固定高度,即height:300px;width:300px去掉
可以用方法一、方法二,方法六,不能使用方法三、方法四,方法五
总结
方法一、方法二对子div的宽高都没有要求,无论有没有指定子div的宽高,都起作用,但对浏览器兼容性有要求
方法三,方法四没有兼容性要求但是只适应于子div高度固定的情况
方法五既对兼容性有要求,同时只适应于div宽高固定的情况
方法六没有兼容性要求,且对子div宽高没有要求,唯一的缺点就是要包裹一层div,html结构会变复杂一些