- line-height 适用于单行文本
.box {
height: 3em;
line-height: 3em;
}
- vertical-align: middle
.pic_box {
width: 300px;
hieght: 300px;
font-size: 0;
}
.pic_box img {
vertical-align: middle;
}
.pic_box:after {
display: inline-block;
width: 0;
height: 100%;
content: '';
vertical-align: middle;
overflow: hidden;
}
注意需要两个同级的inline/inline-block元素vertical-align: middle才能起到真正的居中效果
- display: table-cell
.pic_box {
width: 300px;
height: 300px;
background-color: #beceeb;
display: table-cell;
text-align: center;
vertical-align: middle;
}
- 绝对定位 + margin 1.0
.content {
position: absolute;
top: 50%;
left:50%;
width: 240px;
margin-left: -120px;/* 目标元素的宽度的一半 */
height: 240px;
margin-top: -120px; /* 目标元素的高度的一半 */
}
此方法只适用于固定大小的元素
- 绝对定位 + margin 2.0
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 240px;
width: 70%;
}
- 绝对定位 + transform
.inner{
position : absolute;
top: 50%;
left:50%;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
- display: flex;
.box{
display: flex;
align-items:center;
}
-
浮动元素水平居中的方法
让最外面的浮动层相对定位,left等于50%,然后内部嵌套层也使用相对定位且left设为-50%,这样的效果就是内层相对整行为水平居中
图片.png
网友评论