我需要將多行文本垂直居中放在父項中。我需要孩子成爲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-索引?這也適用於相對定位。 –