【问题标题】:Shrinking <img> when <p> grows and keeping aspect ratio with flex-box<p> 增长时缩小 <img> 并使用 flex-box 保持纵横比
【发布时间】:2017-01-08 03:55:26
【问题描述】:

我有一个静态高度容器。

在里面我有一个div 元素,里面有一个img 元素。

下面有一个p标签,它是动态填充文本的。

当文本较长且p 标签变大时,我希望上面的图像缩小以在容器内腾出空间。

我一直在尝试使用flexflex-shrink 来做到这一点。这就是我所拥有的:

http://codepen.io/niper1/pen/yaBxvx

#main {
  width: 100px;
  height: 200px;
  border: 1px solid #c3c3c3;
  display: -webkit-flex; /* Safari */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
#main div {
  flex-shrink: 3;
}
img {
  height: 100%;
  width: auto;
  max-width: 100%;
}
p {
  flex-shrink: 0;
}
<div id="main">
  <div style="background-color:lightblue;">
    <img src="http://fakeimg.pl/250x100/">
  </div>
  <p>Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text N</p>
</div>

如您所见,img 标记并未缩小以腾出足够的空间。这可能与flex-box有关还是我必须寻找不同的路线?

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    默认情况下,弹性项目不能小于其内容的长度。

    弹性项目的初始大小是min-height: automin-width: auto

    不管flex-shrink,你的弹性项目都不会小于你的图片,除非你用min-height: 0覆盖默认值。 (如果你的容器是行方向的,那就是min-width: 0。)

    此外,并非所有浏览器都将父元素的弹性高度识别为子元素百分比高度的参考。因此,在图像的父级上指定heightflex-basis 很重要。

    #main {
      width: 100px;
      height: 200px;
      border: 1px solid #c3c3c3;
      display: -webkit-flex; /* Safari */
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    
    #main div {
      flex: 1 1 100%;              /* 1 */
      min-height: 0;               /* 2 */
    }
    
    img {
      height: auto;                /* 3 */
      width: 100%;                 /* 3 */
    }
    
    p {
      flex-shrink: 0;
      min-height: 0;               /* 2 */
    }
    <div id="main">
      <div style="background-color:lightblue;">
        <img src="http://fakeimg.pl/250x100/">
      </div>
      <p>Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text Test text N</p>
    </div>

    注意事项:

    1. Chrome / Safari not filling 100% height of flex parent
    2. Why doesn't flex item shrink past content size?
    3. 调整原始代码块

    【讨论】:

    • 感谢您的回复,设置最小高度:0;帮助所以现在它不会流到容器外。但是,使用此解决方案,img 不包含在 div 中(img 在 div 之外流动)。
    • 这里没有看到这种行为。包含图像(至少在 Chrome 中)。也许考虑让 div 也成为一个 flex 容器。
    猜你喜欢
    • 2019-08-03
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2017-12-30
    • 2010-11-25
    • 1970-01-01
    相关资源
    最近更新 更多