我有一个高度为x的受限空间。在这里我有一个未知和可变高度(Z)的div。如果可能的话,我想将它设置为从位置Y(顶部:Y)开始,但是如果高度低于底部,那么我想将它设置为固定底部并向上延伸(底部:0;最大高度: X)。根据div是否溢出,我可以使用CSS将div粘贴到容器的顶部或底部吗?
是否有实现这一目标的一个纯CSS的方式,或者说我必须去JS路线?
我有一个高度为x的受限空间。在这里我有一个未知和可变高度(Z)的div。如果可能的话,我想将它设置为从位置Y(顶部:Y)开始,但是如果高度低于底部,那么我想将它设置为固定底部并向上延伸(底部:0;最大高度: X)。根据div是否溢出,我可以使用CSS将div粘贴到容器的顶部或底部吗?
是否有实现这一目标的一个纯CSS的方式,或者说我必须去JS路线?
这不是最优雅的解决方案,但与间隔元素使用flex
应该做的伎俩。该解决方案仅限于CSS和works in all modern browsers。
(和稍微的下侧)的关键是一个空的隔离件添加到标记来创建顶部偏移,像这样:
<div class="container">
<div class="spacer"></div>
<div class="inner">
A short bit of text.
</div>
</div>
,然后设置.container
到
display: flex;
flex-direction: column;
所以.spacer
和.inner
垂直堆叠。最后,下面的CSS添加到.spacer
元素:
flex: 1;
max-height: 150px; // The amount of offset you want from the top
其中max-height
值是您从顶部想要的间距。
这是在行动:
/* .boxes is only for demo purposes */
.boxes {
display: flex;
justify-content: space-between;
}
.container {
display: flex;
flex-direction: column;
flex: 1;
margin: 0 10px;
height: 300px;
border: 3px solid #222222;
position: relative;
}
.spacer {
flex: 1;
max-height: 150px;
}
.inner {
background-color: red;
box-sizing: border-box;
width: 100%;
font-family: Arial;
color: #ffffff;
padding: 5px;
}
<div class="boxes">
<div class="container">
<div class="spacer"></div>
<div class="inner">
A short bit of text.
</div>
</div>
<div class="container">
<div class="spacer"></div>
<div class="inner">
A medium amount of text to fill a few more rows.
</div>
</div>
<div class="container">
<div class="spacer"></div>
<div class="inner">
A really, really, really, really, really, really really, really, really, really, really, really, really, really, really, really long amount of text to fill the entire height of the element so it forces the inner box to move up.
</div>
</div>
</div>
难道这就是position: sticky
应该解决的问题吗?事情是这样的:
.outer {
height: 300px; /* X */
overflow: auto;
position: relative;
}
.inner {
position: sticky;
bottom: 0;
max-height: 300px; /* X */
overflow: auto;
top: 30px; /* Y */
}
见这里的例子:https://jsfiddle.net/sawox4pa/
它不会在边缘工作/ IE(http://caniuse.com/#search=sticky),但你可以填充工具它为那些浏览器:https://github.com/wilddeer/stickyfill
我觉得没有一个纯CSS的方式,即使有可能是一个天才,也许有些令人费解的方式做到这一点不JS 。我的直觉告诉我,JS提供了一个直接和简单的解决方案,因为它支持条件(CSS,比如媒体查询,但不以这种方式对此有用)。 – Terry
请提供一个[mcve] – TylerH
这就是我一直在尝试的:https://jsfiddle.net/4oejjLxe/(我想要“内部”div从400px开始,如果它的高度小于100px重叠黄色块的末端)) – apkdsmith