我需要将多行文本垂直居中放在父项中。我需要孩子成为position: absolute;
,因为它后面会有其他物品。我无法弄清楚如何让孩子(一个包含文字的div)垂直居中。 (我也试图与display: table-cell
这样做,但无法得到,要么工作)为什么这不是绝对定位的div垂直居中?
https://jsfiddle.net/t7q1ffm2/
HTML:
<div class="box">
<div class="text">This has some text in it that's long</div>
</div>
<div class="box">
<div class="text">Short text</div>
</div>
CSS:
.box
{
position: relative;
top: 0em;
left: 0em;
width: 125px;
height: 125px;
-webkit-flex-grow: 1;
-moz-flex-grow: 1;
-ms-flex-grow: 1;
flex-grow: 1;
margin-right: .625em;
margin-bottom: .5em;
text-decoration: none;
overflow: hidden;
display: table;
background-color: red;
}
.box .text
{
position: absolute;
top: 0;
bottom: 0;
left:0;
right:0;
margin: auto;
width:100%;
height: 50%;
font-family: Arial, Helvetica;
font-size: 1em;
font-weight: normal;
line-height: 1.125em;
color: #ffffff;
text-align: center;
z-index: 2;
}
因为你设置的.text的高度为50%。 – j08691
'top:0' so .... that's not centered。 – GolezTrol
“位置:绝对”不能用于Flexbox儿童。为什么你会'需要'它被绝对定位为给它一个z-索引?这也适用于相对定位。 –