首页 > 解决方案 > 在 Div 中堆叠图像和文本,允许文本控制 Div 中的高度

问题描述

我有一个固定的高度 div。在该 div 中,我想在文本顶部堆叠图像。我希望文本区域控制图像有多少空间。我只想用 CSS 来做这件事。我确信我可以设计一个带有 JS 的系统,但我试图在这种情况下避免它。

更多细节:

如果文本需要三行,那么上面的图像应该max-width: 100%并且max-height不超过所占用文本空间的剩余部分。因此,如果父 div 为 750px 且文本需要 100px 的高度,则图像最多应允许为 650px 高。

我一直在搞乱 flex-box 之类的东西,试图使用 flex-column 之类的东西,但我无法限制图像的大小。我堆叠了 2 个 div 区域,顶部随着文本而缩小,但是当我将图像放入时,它就坏了。

这甚至可以单独使用 CSS 实现吗?

这就是我所拥有的以及它不起作用的示例:https ://jsfiddle.net/aoqerm06/

<div style="height: 400px;" class="d-flex flex-column">
    <div class="bg-primary h-100" >
        IMAGE GOES HERE
    </div>
    <div class="flex-grow-1">
        LOTS OF TEXT HERE
    </div>
</div>

标签: cssbootstrap-4

解决方案


我想我已经找到了你要找的东西。通过将其制作成带有 bg-image 的 div,您可以更轻松地对其进行操作:

.ex-container {
  display: flex;
}
.container {
  display: flex;
  flex-direction: column;
  padding: 10px;
  height: 450px;
  width: 300px;
  background-color: #ddd;
  margin-right: 15px;
}

.text {
  
}

.img {
  display: inline-block;
  height: 100%;
  width: 100%;
  background-image: url('https://source.unsplash.com/random');
  background-size: 100%;
  background-position: center;
  background-repeat: no-repeat;
}
<div class="ex-container">
  <div class="container">
    <div class="text">
      <p>Lots of text here. Lots of text here. Lots of text here. Lots of text here. Lots of text here. </p>
    </div>
    <div class="img"></div>
  </div>
  
  <div class="container">
    <div class="img"></div>
    <div class="text">
      <p>Lots of text here. Lots of text here. Lots of text here. Lots of text here. Lots of text here.Lots of text here. Lots of text here. Lots of text here. Lots of text here. Lots of text here.Lots of text here. Lots of text here. Lots of text here. Lots of text here. Lots of text here.Lots of text here. Lots of text here. Lots of text here. Lots of text here. Lots of text here.  Lots of text here. Lots of text here.Lots of text here. Lots of text here. Lots of text here. Lots of text here. Lots of text here.</p>
    </div>
    
  </div>
</div>


推荐阅读