div中内容上下居中
情形一:div限高,内容长度限一行
代码:
复制代码 代码示例:
<style>
.v-align {
margin: 0 auto;
width: 200px;
height: 80px;
text-align: center;
line-height: 80px;
border: 1px solid #ddd;
}
</style>
<!-- html -->
<div class="v-align">我的内容只能有一行。</div>
如图:

情形二:div限高,内容不限
复制代码 代码示例:
.v-mult {
margin: 0 auto;
width: 200px;
height: 100px;
border: 1px solid #ddd;
overflow: hidden;
}
.v-mult .empty,
.v-mult .text {
display: inline-block;
*display: inline;
*zoom: 1;
vertical-align: middle;
}
.v-mult .empty {
height: 100%;
}
<!-- html -->
<div class="v-mult">
<span class="empty"></span>
<span class="text">我的内容不限,多高都行
换行照常</span>
</div>
如图:

情形三:div高度不定,内容高度一定
代码:
复制代码 代码示例:
.v-auto {
position: relative;
margin: 0 auto;
width: 200px;
border: 1px solid #ddd;
}
.v-auto .text {
position: absolute;
top: 50%;
margin-top: -50px;
height: 100px;
border: 1px dashed #ddd;
}
<!-- html -->
<div class="v-auto">
<div class="text">
我的高度是固定的,只有100px高,但是父级高度不定,怎么
垂直居中呢?
</div>
</div>
如图:

情形四:div高度不定,内容高度不定。
代码:
复制代码 代码示例:
.v-auto-out {
position: relative;
margin: 0 auto;
width: 200px;
border: 1px solid #ddd;
}
.v-auto-out .auto-in {
position: absolute;
top: 50%;
border: 1px dashed #ddd;
/* 这里有兼容性问题 */
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
-o-transform: translateY(-50%);
transform: translateY(-50%);
}
<!-- html -->
<div class="v-auto-out">
<div class="auto-in">我的高度不定,我的父及高度也不定,这下要上下居中,该如何是好?我们一起来瞧瞧吧。</div>
</div>
如图:
