代码之家  ›  专栏  ›  技术社区  ›  Audun Olsen

当受父级约束时,两行布局中的CSS最大宽度图像应收缩

  •  0
  • Audun Olsen  · 技术社区  · 5 年前

    我有一个图像(顶行)和一个标题(底行),图像的最大宽度为400像素。两行都在最大高度为100vh的包装器内。就像现在的代码一样,当包装器的内容受视口约束时,它的内容将溢出。理想情况下,图像应该缩小(保持纵横比),而标题在底部仍然可见。

    HTML格式:

    <div class="wrapper">
      <picture>
        <img src="https://images.theconversation.com/files/350865/original/file-20200803-24-50u91u.jpg?ixlib=rb-1.1.0&q=45&auto=format&w=1200&h=1200.0&fit=crop" />
      </picture>
      <div class="caption">This is a responsible cat</div>
    </div>
    

    html, body { height: 100%; }
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      background: #202227;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fafafa;
      border: 2px solid pink;
      text-align: center;
    }
    
    .wrapper {
      padding: 10px;
      max-height: 100vh;
      background: #37393d;
      border: 5px solid #36badd;
    }
    
    img {
      width: 100%;
      max-width: 400px;
    }
    

    jsiddle演示: https://jsfiddle.net/audunolsen/w30e4sgq/17/

    1 回复  |  直到 5 年前
        1
  •  1
  •   MoritzLost    5 年前

    max-height 总是用父母的身高, 它的 最大高度 this answer ). 相反,添加 max-height: 100vh

    更新的小提琴: https://jsfiddle.net/qw70tr2f/1/

    推荐文章