You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让图片高度与包含引用及署名的兄弟div保持一致?

如何让图片高度与包含引用内容的兄弟div完全一致?

先看最初尝试的代码,想用flex布局让图片和文本div等高:

.fancyquote {
  display: flex;
  align-items: stretch;
}

img {
  height: 100%;
  object-fit: cover;
}
<div class="fancyquote">
  <img src="https://placehold.co/256x256?text=Author\nPhoto"/>
  <div>
    <blockquote>Some people have a way with words, and other people...oh, uh, not have way.</blockquote>
    <cite>Steve Martin</cite>
  </div>
</div>

但这个方案有个局限:只有给图片手动设置宽度时,高度才会跟着兄弟div拉伸,没法自动匹配高度。

解决方法

给图片套一个容器,利用定位让图片填满容器,而容器会被flex布局自动拉伸到和文本div一样的高度:

.fancyquote {
  display: flex;
  align-items: stretch;
}

.img-wrap {
  position: relative;
  overflow: auto;
  /* 可根据需求给容器设置宽度,比如 width: 200px; 控制图片区域宽度 */
}

img {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  object-fit: cover; /* 保证图片比例不变,避免拉伸变形 */
}
<div class="fancyquote">
  <div class="img-wrap">
    <img src="https://placehold.co/256x256?text=Author\nPhoto"/>
  </div>
  <div>
    <blockquote>Some people have a way with words, and other people...oh, uh, not have way.</blockquote>
    <cite>Steve Martin</cite>
  </div>
</div>

原理很简单:flex布局的align-items: stretch会让所有flex子项(.img-wrap和文本div)高度一致,绝对定位的图片会填满.img-wrap的整个空间,这样图片高度就和文本div完全匹配了,不用依赖图片自身的宽度设置。

内容的提问来源于stack exchange,提问作者Dan Grahn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 10:03:26