我想将动态高度div从父级顶部转换到中心。
有多种方法可以将具有动态高度的div垂直对齐到其父级的中心,例如使用CSS表+ vertical-align:middle
或flexbox - 但问题是vertical-align:middle
和flexbox {{ 1}}属性不是animatable properties。
看看:
align-items
vertical-align:middle
.block {
display: table;
width: 100%;
height: 150px;
}
.centered {
display: table-cell;
vertical-align: top;
background: pink;
-webkit-transition: all .5s;
-moz-transition: all .5s;
-o-transition: all .5s;
transition: all .5s;
}
.block:hover .centered {
vertical-align: middle;
}
和
<div class="block">
<div class="centered">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit
</div>
</div>
.block {
background: orange;
height: 150px;
display: flex;
align-items: flex-start;
-webkit-transition: all .5s;
-moz-transition: all .5s;
-o-transition: all .5s;
transition: all .5s;
}
.centered {
text-align: center;
background: pink;
top: 0;
}
.block:hover {
align-items: center;
/* align vertical */
}
是否存在支持从顶部到中心过渡的垂直居中方法?
答案 0 :(得分:4)
此transform: translateY(-50%);
方法效果很好。
<强> FIDDLE 强>
.block {
background: orange;
height: 150px;
}
.centered {
text-align: center;
background: pink;
position: relative;
top: 0;
-webkit-transition: all .5s;
-moz-transition: all .5s;
-o-transition: all .5s;
transition: all .5s;
}
.block:hover .centered {
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
top: 50%;
}
&#13;
<div class="block">
<div class="centered">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna</div>
</div>
&#13;