2017-10-10 119 views
2

我有一个高度为x的受限空间。在这里我有一个未知和可变高度(Z)的div。如果可能的话,我想将它设置为从位置Y(顶部:Y)开始,但是如果高度低于底部,那么我想将它设置为固定底部并向上延伸(底部:0;最大高度: X)。根据div是否溢出,我可以使用CSS将div粘贴到容器的顶部或底部吗?

enter image description here

是否有实现这一目标的一个纯CSS的方式,或者说我必须去JS路线?

+1

我觉得没有一个纯CSS的方式,即使有可能是一个天才,也许有些令人费解的方式做到这一点不JS 。我的直觉告诉我,JS提供了一个直接和简单的解决方案,因为它支持条件(CSS,比如媒体查询,但不以这种方式对此有用)。 – Terry

+1

请提供一个[mcve] – TylerH

+0

这就是我一直在尝试的:https://jsfiddle.net/4oejjLxe/(我想要“内部”div从400px开始,如果它的高度小于100px重叠黄色块的末端)) – apkdsmith

回答

3

这不是最优雅的解决方案,但与间隔元素使用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>

相关问题