【问题标题】:How to an shrink image to fit inside of a container with no set width如何缩小图像以适合没有设置宽度的容器内部
【发布时间】:2021-12-28 02:09:30
【问题描述】:

我有一些图片卡片,每张卡片都有一张图片和一些文字。这些卡片的大小由它们包含的图像的高度决定。如果视口宽度太小以至于图像的设置高度会使图像水平溢出,我希望图像缩小以使其保持在卡片/视口内

.card {
  width: fit-content;
  max-width: 100%;
  background-color: lightgray;
  padding: 1em;
}

img {
  height: 13em;
}
<div class="card">
  <img src="https://cdn.sstatic.net/Img/teams/teams-illo-free-sidebar-promo.svg?v=47faa659a05e" alt="random image...">
</div>

我知道我可以使用媒体查询,但我想知道是否有更好的方法来解决这个问题。

【问题讨论】:

    标签: html css image


    【解决方案1】:

    有几种方法可以使图像适合&lt;div&gt;

    img {
        object-fit: cover;
    }
    

    CSS object-fit 属性用于指定如何调整 or 的大小以适应其容器。

    更多详情,请访问thread

    【讨论】:

      【解决方案2】:

      虽然您可以将 img 的最大宽度设置为视口宽度,但如果高度固定,则会扭曲图像。

      为了确保宽度不超过视口宽度且高度不超过 13em,此 sn-p 将宽度和高度都设置为最大值。而且它没有明确设置高度。

      注意:它通过设置 box-sizing:border-box 以及删除任何浏览器默认边距和填充来保持视口内的 padding + img。

      <style>
      * {
        padding: 0;
        margin: 0;
        box-sizing: border-box;
      }
      .card {
        width: fit-content;
        max-width: 100vw;
        background-color: lightgray;
        padding: 1em;
      }
      
      .card img {
        max-height: 13em;
        max-width: calc(100vw - 2em);
      }
      </style>
      <div class="card">
        <img src="https://picsum.photos/id/1016/4000/500" alt="random image...">
      </div>

      【讨论】:

        【解决方案3】:

        我认为您必须使图像响应最大宽度。我认为这会有所帮助

        img {
              max-width:100%;
              height: 13em;
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-07
          • 1970-01-01
          • 2012-05-07
          • 2013-10-16
          • 1970-01-01
          • 2019-05-06
          • 2017-08-08
          • 2018-10-19
          相关资源
          最近更新 更多