悬停时纯 CSS3 动画上滑标题

Oli*_*ler 3 html css frontend css-animations

背景非常简单,当用户悬停/点击时,我希望从元素底部向上滑动一个小标题。见图 1。

图 1,文本在悬停时向上滑动

有点挖掘说这不能使用 CSS 来完成,但我真的不明白为什么。几个小时后,我想我已经非常接近解决它了,但我无法跨越最后的障碍。

我的逻辑是,如果您的父元素有overflow: hidden,并且您绝对将标题放置在父元素的底部之外,则可以使用 transition 属性为位置值设置动画,使其向上滑动。纯CSS宝贝!

你不能动画高度 - 文本被压碎,元素必须作为一个块移动(尽管不一定呈现为 display:block)。

到目前为止,我已经到了https://jsfiddle.net/zufwavpn/。HTML,

<div class="item-wrapper">
  <div class="content">
    Hello I am content. All that matters for this method to work is that the item wrapper has a fixed size. In my working project, the width is set to a % value, and the height to rem.
  </div>
  <div class="popup-title">
    <span>A title for my content</span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和 CSS(我已经在这里转换为 vanilla CSS),

.item-wrapper{
    height:22rem;
    position:relative;
    overflow:hidden;
    color:white;
    font-family:sans-serif;
  }

  .content{
    height:100%;
    background-color:red;
    padding:10px;
  }

  .popup-title{
    position:absolute;
    top:100%;
    bottom:0%;
    width:100%;
    transition: bottom 0.5s, top 0.5s;
    vertical-align: bottom;
  }

.popup-title span{
    display:block;
    margin:0;
    background-color: black;
}

.item-wrapper:hover .popup-title{
    bottom:0%;
    top:0%;
}
Run Code Online (Sandbox Code Playgroud)

感觉很接近的原因是,在这个阶段,popup基本可以工作,但是里面的内容应该和容器底部对齐。从本质上讲,这是将绝对定位元素的顶部和底部设置为“0”的古老技巧,但用于从容器下方为某些内容设置动画。

为什么我要为顶部和底部属性设置动画?如果您只使用 'top' 值,您可以通过设置隐藏元素top:100%,但您不能为其设置动画,因此它会停留在父项的底部。您需要将顶部的特定值设置为(父项的高度减去弹出内容的高度),并且弹出内容/父项可以是任何大小。您可以设置bottom:-100%- 这实际上有效,您可以为 设置动画bottom:0%,并在父级底部弹出其余部分。一切都很好,无需设置最高值。但是,令人不满意的是,您必须将滑块放在父级下方并为其设置动画,由于与其他动画有关的各种原因,这会产生不合时宜的效果。

因此,这里我们将弹出元素定位在父元素的底部,由于顶部和底部值重合,因此没有高度,并且内容向下溢出。完美的。然后顶部值动画起来,弹出元素现在有top:0; bottom:0,填充父元素,如果我能让内容粘在底部,一切都会好起来的。

最后一点通常不太难。我们有垂直对齐和整个 flex 世界,但它们似乎都会产生错误和错误,让我陷入困境。任何人的想法?在这一点上,我必须继续前进,只使用 javascript,但我觉得这是一个值得自己解决的问题。

Maj*_*aju 5

.item-wrapper {
  height:22rem;
  position:relative;
  overflow:hidden;
  color:white;
  font-family:sans-serif;
}

.content {
  height:100%;
  background-color:red;
  padding:10px;
}

.popup-title {
  position:absolute;
  top:100%;
  width:100%;
  transition: transform 250ms;
  vertical-align: bottom;
}
.popup-title span {
  display:block;
  margin:0;
  background-color: black;
}

.item-wrapper:hover .popup-title {
  transform:translateY(-100%);
}
Run Code Online (Sandbox Code Playgroud)
<div class="item-wrapper">
  <div class="content">
    Hello I am content. All that matters for this method to work is that the item wrapper has a fixed size. In my working project, the width is set to a % value, and the height to rem.
  </div>
  <div class="popup-title">
    <span>A title for my content</span>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)