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

标签 css css-transitions vertical-alignment

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

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

看一下:

CSS 表格 + vertical-align:middle

<强> FIDDLE

.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>

flex 盒

<强> FIDDLE

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

</div>

有没有一种垂直居中的方法,支持从上到中的过渡?

最佳答案

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

关于css - 将动态高度 div 从顶部过渡到垂直中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26464147/

相关文章:

html - 如何让这个 <SPAN> 元素跨越 100% 的 LI?

javascript - only one root element is allowed 动态创建div时出错

jquery - Bootstrap 导航栏宽度的动画

javascript - div 的 CSS 过渡没有动画效果

html - 垂直对齐 Bootstrap 复选框

css - 显示 Div 边框而不是父级

CSS3 过渡不起作用

CSS3 : animated sprite + on hover transition

html - 为什么垂直对齐是:middle not aligning things in my table row?

html - 如何使用 css 居中并排显示文本链接?