背景非常简单,我想在用户悬停/点击时从元素底部向上滑动一个小标题。见图 1。
一点挖掘说这不能使用 CSS 完成,但我真的不明白为什么。几个小时后,我认为我已经非常接近解决它了,但我无法跨越最后的障碍。
我的逻辑是,如果你的父元素有 overflow: hidden
,并且你绝对将标题放在父元素的底部之外,你可以使用 transition 属性为位置值设置动画,以便它滑动向上。纯 CSS 宝贝!
您不能设置高度动画 - 文本被压碎,元素必须作为一个 block 移动(尽管不一定呈现为 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>
还有 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%;
}
之所以感觉接近,是因为在这个阶段,popup基本可以了,但是里面的内容应该是和容器底部对齐的。本质上,这是将绝对定位元素的顶部和底部设置为“0”但用于从容器下方设置动画的古老技巧。
为什么要为顶部和底部属性设置动画?如果您只使用“top”值,您可以通过设置 top:100%
来隐藏该元素,但您无法为其设置动画,因此它将停留在 parent 的底部。您需要将顶部的特定值设置为(父项的高度减去弹出内容的高度),并且弹出内容/父项可以是任何大小。您可以设置 bottom:-100%
- 这确实有效,您可以设置 bottom:0%
的动画,并在父项的底部弹出其余部分。一切顺利,无需设置最高值。但是,它并不令人满意,您必须将 slider 放置在父级下方并为其设置动画,由于与其他动画有关的各种原因,这会产生错误的时间效果。
因此,此处弹出元素位于父元素的底部,没有高度,因为顶部和底部值重合,内容向下溢出。完美的。然后 top 值向上动画,弹出元素现在有 top:0; bottom:0
,填充父级,如果我能让内容粘在底部就好了。
这最后一点通常不会太难。我们有 vertical-align 和整个 flex 世界,但它们似乎都会产生错误和错误,让我陷入困境。有什么想法吗?在这一点上,我必须继续使用 javascript,但我觉得这是一个值得单独解决的问题。
最佳答案
.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%);
}
<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>
关于html - 悬停时纯 CSS3 动画上滑字幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39007424/