1、对于单行文字相对于容器居中且容器高度确定,直接设置容器的line-height属性值等于容器的height,这个大家都知道
2、图片相对容器居中
<div id="box">
<img src="duncan.jpeg">
</div>
#box{
width: 300px;
height: 300px;
line-height: 300px;
}
#box img {
vertical-align: middle;
}
3、对于多行文字相对于容器居中且容器高度确定,可以使用display和vertical-align,其实更多还是会用padding,如第4点
.wrap{
background:#ccc;
display:table;
vertical-align:middle;
}
<div class="wrap">
<p>Hello world</p>
<p>Hello world</p>
<p>Hello world</p>
</div>
4、对父元素设置padding,不能设置父元素的高度,让父元素的高度自适应
<div id="box">
<div id="child">测试文字</div>
</div>
#box {
padding: 100px 0;
}
#child {
width: 200px;
height: 100px
}
5、transform 加 绝对定位-------不需要知道子元素的高度
<div id="box">
<div id="child">测试文字</div>
</div>
#box {
width: 300px;
height: 300px;
position: relative;
}
#child {
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
6、绝对定位加负外边距---------必须知道子元素的高度
<div id="box">
<div id="child">我是测试DIV</div>
</div>
#box {
width: 300px;
height: 300px;
position: relative;
}
#child {
width: 150px;
height: 100px;
position: absolute;
top: 50%;
margin: -50px 0 0 0;
}
7、使用display: flex;和align-items: center;-------适合行内元素和块级元素
<div id="box">测试文字</div>
#box {
width: 300px;
height: 300px;
display: flex;
align-items: center;
}
8、使用display: flex;flex-direction: column; justify-content: center;-------适合行内元素和块级元素
<div id="box">
<div id="child">
测试文字
</div>
</div>
#box {
width: 300px;
height: 300px;
display: flex;
flex-direction: column;
justify-content: center;
}
9、使用绝对定位加margin: auto----子元素的top和bottom必须设为一样的值,不管什么值都可以。子元素可以不设置高度
<div id="box">
<div id="child">测试文字</div>
</div>
#box {
width: 300px;
height: 300px;
position: relative;
}
#child {
background: #A1CCFE;
position: absolute;
top: 0;
bottom: 0;
margin: auto;
}
10、伪类元素加vertical-align:middle; display:inline-block----容器高度不确定
<div class="comm" >
<span class="text">测试文字</span>
</div>
.comm {
height:100%;
}
.text {
display: inline-block;
}
.text:before {
display: inline-block;
height: 100%;
width: 0;
vertical-align: middle;
}