文章目录
css常用的垂直居中
这里是引用
1.父相子绝–给定子盒子的尺寸(margin
)
父盒子相对定位,子盒子绝对定位
使用前提
必须提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中。
效果如图
css代码
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 150px;
height: 100px;
background: orange;
position: absolute;
top: 50%;
margin: -50px 0 0 0;
}
html代码
<div id="box">
<div id="child"></div>
</div>
2.父相子绝–可以不给定子盒子的尺寸(transform
)
transform 中 translate 偏移的百分比就是相对于元素自身的尺寸而言的。
<div id="box">
<div id="child">test vertical align</div>
</div>
css代码
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
background: orange;
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
3.父相子绝–(margin: auto
)
前提
知道元素的宽高,图片这种自身就包含尺寸的元素不用设置
top和bottom设为相等的值,只要两者相等就行
css代码
#box {
width: 300px;
height: 300px;
background: #ddd;
position: relative;
}
#child {
width: 200px;
height: 100px;
background: orange;
position: absolute;
top: 0;
bottom: 0;
margin: auto;
line-height: 100px;
}
html代码
<div id="box">
<div id="child">test vertical align</div>
</div>
4. 父元素使用(padding
)
前提
父元素是不能设置高度的,要让它自动被填充起来,除非设置了一个正好等于上内边距+子元素高度+下内边距的值,否则无法精确垂直居中。
css代码
#box {
width: 300px;
background: #ddd;
padding: 100px 0;
}
#child {
width: 200px;
height: 100px;
background: orange;
}
html
<div id="box">
<div id="child"></div>
</div>
5. 父盒子使用flex布局
flex布局参考文章
http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html
适用于行内元素与块级元素
css
#box {
width: 300px;
height: 300px;
background: #ddd;
display: flex;
align-items: center;
}
#child {
width: 300px;
height: 100px;
background: orange;
}
html
<div id="box">
<div id="child"></div>
</div>
6.单行文本居中
line-height等于height
#box{
width: 300px;
height: 300px;
background: #ddd;
line-height: 300px;
}
7. 图片居中
使用 line-height 和 vertical-align 对图片进行垂直居中
css
#box{
width: 300px;
height: 300px;
background: #ddd;
line-height: 300px;
}
#box img {
width: 200px;
height: 200px;
vertical-align: middle;
}
html
<div id="box">
<img src="smallpotato.jpg">
</div>
8. 对容器里的文字进行垂直居中
使用 display: table; 和 vertical-align: middle;
css
#box {
width: 300px;
height: 300px;
background: #ddd;
display: table;
}
#child {
display: table-cell;
vertical-align: middle;
}
html
<div id="box">
<div id="child">test vertical align</div>
</div>