盒模型垂直水平居中的方法总结
基本结构如下:
<div class="father">
<div class="son"></div>
</div>
1.使用margin指定具体值垂直水平居中
注意:此处简化说明,只给了父元素、子元素一个宽度,使用具体值时,应加上父元素、子元素的border的值。
需要指定margin-top、margin-left的值。把值写死,维护性差。
样式如下:
.father{
background-color:lightblue;
width: 300px;
height: 300px;
position:relative;
}
.son{
background-color: blueviolet;
height: 100px;
width: 100px;
position:absolute;
top:50%;
left:50%;
margin-top:-50px;/*自身的一半*/
margin-left:-50px;
}
2.使用position + margin垂直水平居中
非常常用的一种方法
.father{
background-color:lightblue;
width: 300px;
height: 300px;
position:relative;
}
.son{
background-color: blueviolet;
height: 100px;
width: 100px;
position:absolute;
top:0px;
left:0px;
right:0px;
bottom:0px;
margin:auto;
}
3.使用flex + margin垂直水平居中
.father{
background-color:lightblue;
width: 300px;
height: 300px;
display:flex;
}
.son{
background-color: blueviolet;
height: 100px;
width: 100px;
margin:auto;
}
4.使用flex+ justify-content或align-items垂直水平居中
注意:justify-content、align-items 为css3新布局方式,注意浏览器的兼容性。
IE9及IE9以下不兼容
.father {
background-color: lightblue;
width: 300px;
height: 300px;
display: flex;
justify-content: center;/*设置水平方向*/
align-items: center;/*设置垂直方向*/
}
.son {
background-color: blueviolet;
height: 100px;
width: 100px;
}
5.使用position定位 + transform垂直水平居中
注意:transform为 css3 新布局方式,注意浏览器的兼容性。
.father {
background-color: lightblue;
width: 300px;
height: 300px;
position:relative;
}
.son {
background-color: blueviolet;
height: 100px;
width: 100px;
position: absolute;
top:50%;
left: 50%;
transform:translate(-50%, -50%);
}
6.利用table-cell垂直水平居中
.father {
background-color: lightblue;
width: 300px;
height: 300px;
vertical-align: middle;
display: table-cell;
text-align: center;
}
.son {
background-color: blueviolet;
height: 100px;
width: 100px;
display:inline-block
}
7.补充:使用行内块 + text-align 水平居中
.father {
background-color: lightblue;
width: 300px;
height: 300px;
text-align: center;
}
.son {
background-color: blueviolet;
height: 100px;
width: 100px;
display: inline-block;
}