将动态高度div从顶部过渡到垂直中心

时间:2014-10-20 11:06:18

标签: css css3 css-transitions vertical-alignment

我想将动态高度div从父级顶部转换到中心。

有多种方法可以将具有动态高度的div垂直对齐到其父级的中心,例如使用CSS表+ vertical-align:middle或flexbox - 但问题是vertical-align:middle和flexbox {{ 1}}属性不是animatable properties

看看:

CSS表格+ align-items

FIDDLE

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;
}

Flexbox的

FIDDLE

<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 */
 }

是否存在支持从顶部到中心过渡的垂直居中方法?

1 个答案:

答案 0 :(得分:4)

transform: translateY(-50%);方法效果很好。

<强> FIDDLE

&#13;
&#13;
.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;
&#13;
&#13;