如何使用CSS将元素向上移动至可变高度

Ale*_*min 4 html css markup stylesheet

主要问题

我有两个div,一个嵌套在另一个div中,我希望将内部div向外(向上)移到外部div上,然后将其滑入。

标记看起来像这样:

<div class="body">
    <div class="inner">Green is variable-height text which slides in on viewport hover</div>
    Blue is a viewport (&lt;body&gt;, visible part of a page), which content should be compressed upon green slide-in
</div>
Run Code Online (Sandbox Code Playgroud)

和(一点伪)CSS:

.body {
    background: #aaf;
    height: 300px;
    width: 300px;
    overflow: hidden;
}

.inner, .body:hover .inner {
    -webkit-transition:all linear 0.2s;
    transition:all linear 0.2s;
}

.inner {
    background: #afa;
    width: 300px;
    margin-top:-some-magic-to-get-this-div-height;
}

.body:hover .inner {
    margin-top: 0;
}
Run Code Online (Sandbox Code Playgroud)

我想得到一个最终结果动画,而无需使用固定高度的绿色div:

example.gif

另外,在jsfiddle上,该示例(高度值的猜测和硬编码为2.5em)可以进行以下实验:

http://jsfiddle.net/n7vyLoh4/20/

可能的部分解决方法(不令人满意)

它可以部分地实现我想要的东西,使用过渡最大高度,而不是过渡边距,过渡max-height: 0; - > max-height: 100%;同overflow: hidden;组在任何时候都工作,但有两个平局后卫:

  1. 它不会滑入,更像是掉下窗帘
  2. 它不会在绿色div的末尾处停止过渡,而是过渡到外部蓝色div的末尾,这在反向过渡时尤为明显,因为它首先从蓝色div的底部一直移动到绿色div的底部,然后才生效。是可见的。同样,这意味着尽管过渡时间设置为0.2s,但它仅将这段时间的一部分花费在过渡槽绿色div上,因为这100%是父div的100%,而不是内部div(如果存在,我的问题可以回答是一种计算内部div高度的100%的方法。

这是一个例子:

example2.gif

并为此弄弄:

http://jsfiddle.net/bsd7vnwu/1/

sko*_*jic 5

这是纯粹的css解决方案,这意味着它不需要任何脚本,只需一个支持过渡的浏览器即可:

.body {
    background: #aaf;
    height: 300px;
    width: 300px;
    overflow: hidden;
}

.inner {
    -webkit-transition:all cubic-bezier(0,.81,.4,1) 0.5s;
    transition:all cubic-bezier(0,.81,.4,1) 0.5s;
}

.inner {
    background: #afa;
    width: 300px;
    position: absolute;
    margin-top: -100%;
    float: left;
}

.body:hover .inner {
    position: relative;
    margin-top: 0;
}
Run Code Online (Sandbox Code Playgroud)

小提琴在这里


Ali*_*guy 4

我想这就是你想要的效果。CSS 不允许您获取用于calc()定位和边距的元素的高度,因此需要一点 JS。

CSS:

.body {
    background: #aaf;
    height: 300px;
    width: 300px;
    overflow: hidden;
}

.inner, .body:hover .inner {
    -webkit-transition:all linear 0.2s;
    transition:all linear 0.2s;
}

.inner {
    background: #afa;
    width: 300px;
    overflow: hidden;
}

.body:hover .inner {
    margin-top : 0 !important;
}
Run Code Online (Sandbox Code Playgroud)

JS:

Array.prototype.forEach.call(document.getElementsByClassName('inner'), function (item) {
    item.style.marginTop = (item.clientHeight * -1) + 'px';
});
Run Code Online (Sandbox Code Playgroud)

演示:

http://jsfiddle.net/09tyLr9b/