Flexbox 高度基于第一列中的内容

Osc*_*car 2 html css flexbox

我正在尝试创建一个“面板”,它分为两个等宽的列,第一个包含文本,第二个包含图像。图像很大,应缩小以覆盖右侧。面板的高度应遵循左侧的文本量。

它应该是这样的

这就是它应该看起来的样子,图像正在使用,object-fit: cover;以便它完全填充其容器,但我不想max-height: 200px;在 .panel 上

这是否可能以某种方式实现(最好不使用 JavaScript)?

.panel {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: red;

  /* I want this to be flexible based on text in panelText */
  /*max-height: 200px;*/
  
}
.panel .panelText {
  padding: 1em;
  flex: 1;
  width: 50%;
  background-color: black;
  color: white;
}
.panel .panelImage {
  object-fit: cover;
  width: 50%;
}
Run Code Online (Sandbox Code Playgroud)
<section class="panel">
  <div class="panelText">
    <h3>This is a header</h3>

    <ul>
      <li>One one one</li>
      <li>Two two two</li>
      <li>Three three three</li>
      <li>Four four four</li>
    </ul>

    <p>Now we're at the end</p>
  </div>

  <img class="panelImage" src="https://placebear.com/1000/1000" />

</section>
Run Code Online (Sandbox Code Playgroud)

Sen*_*the 6

这是可能的,但你不应该让图像决定其容器的大小 - make it position: absolute。Flex 容器总是会调整到最大的元素,所以object-fit: cover在这里毫无意义。

或者,我建议您使用该图像作为 div 的背景图像(如果它在您的网站设置中可行)。

第一个解决方案在这里:

.panel {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: red;      
}
.panel .panelText {
  padding: 1em;
  flex: 1;
  width: 50%;
  background-color: black;
  color: white;
}
.panel .panelImage {
  position: absolute;
  height: auto;
  width: 100%;
  top: 50%;
  transform: translateY(-50%);
}
.panel .image-wrapper {
  position: relative;
  width: 50%;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)
<section class="panel">
  <div class="panelText">
    <h3>This is a header</h3>

    <ul>
      <li>One one one</li>
      <li>Two two two</li>
      <li>Three three three</li>
      <li>Four four four</li>
    </ul>

    <p>Now we're at the end</p>
  </div>
  <div class="image-wrapper">
    <img class="panelImage" src="https://placebear.com/1000/1000" />
  </div>
</section>
Run Code Online (Sandbox Code Playgroud)

第二种解决方案 - 背景图像:

.panel {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: red;      
}
.panel .panelText {
  padding: 1em;
  flex: 1;
  width: 50%;
  background-color: black;
  color: white;
}
.panel .image {
  width: 50%;
  background-image: url('https://placebear.com/1000/1000');
  background-size: cover;
  background-position: center center;
}
Run Code Online (Sandbox Code Playgroud)
<section class="panel">
  <div class="panelText">
    <h3>This is a header</h3>

    <ul>
      <li>One one one</li>
      <li>Two two two</li>
      <li>Three three three</li>
      <li>Four four four</li>
    </ul>

    <p>Now we're at the end</p>
  </div>
  <div class="image">
  </div>
</section>
Run Code Online (Sandbox Code Playgroud)