【问题标题】:CSS flex a content-fit image with a title sibling of unknown height [duplicate]CSS flex一个带有未知高度的标题兄弟的内容适合图像[重复]
【发布时间】:2020-12-11 21:23:45
【问题描述】:

我正在尝试在 flex-column 中调整 img.title 元素。当页面被调整大小时,图像应该在保持其纵横比的同时扩大/缩小,并且标题文本应该在屏幕底部保持相同的高度。但是,当我降低屏幕高度时,标题文本会被推离屏幕。

另外,.title 元素的高度可能并不总是单行,在渲染之前不会知道。

代码:https://jsfiddle.net/qk4wbfpe/

body {
    
    height: 100vh;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

.container {
    
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
}

.container > img {
    
    flex-grow: 1;
    flex-shrink: 1;
    background-color: blue;
    width: 100%;
    height: 100%;
    object-fit: contain;
}

.container .title {
    
    padding: 10px;
    color: white;
    text-align: center;
    background-color: gray;
}
<div class="container">
    <img src="https://cdn.mos.cms.futurecdn.net/paWPwF85Vkcs8YUuyvA3YM-650-80.jpg.webp">
    <div class="title">
        Planet Earth
    </div>
</div>

【问题讨论】:

    标签: javascript css image flexbox responsive-design


    【解决方案1】:

    为您的容器添加一个包装,使其流畅地流动

    .container {    
    display: flex;
    
    flex-wrap: wrap;
    
    flex-direction: column;
    width: 100%;
    height: 100%;
    

    并为您的孩子添加一个 flex-basis (img)

    .container > img {    
    flex-grow: 1;
    flex-shrink: 1;
    
    flex-basis: 25%;
    
    background-color: blue;
    object-fit: contain;
    

    或者您可以删除 flex-grow、shrink 并将其简写为

    flex: 1 1 25%;
    

    这是你需要的吗?

    【讨论】:

      【解决方案2】:

      如果您将min-height:0 添加到.container&gt;img,它将得到所需的结果。

      body {
        height: 100vh;
        margin: 0;
        padding: 0;
        overflow: hidden;
      }
      
      .container {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 100%;
      }
      
      .container>img {
        flex-grow: 1;
        flex-shrink: 1;
        background-color: blue;
        width: 100%;
        min-height:0;
        object-fit: contain;
      }
      
      .container .title {
        padding: 10px;
        color: white;
        text-align: center;
        background-color: gray;
      }
      <div class="container">
        <img src="https://cdn.mos.cms.futurecdn.net/paWPwF85Vkcs8YUuyvA3YM-650-80.jpg.webp">
        <div class="title">
          Planet Earth
        </div>
      </div>

      【讨论】:

        猜你喜欢
        • 2015-05-15
        • 1970-01-01
        • 1970-01-01
        • 2022-12-11
        • 1970-01-01
        • 2016-04-02
        • 2014-02-09
        • 2018-07-25
        • 2020-11-16
        相关资源
        最近更新 更多