【问题标题】:Responsive Image with Max-height & Max-width具有最大高度和最大宽度的响应式图像
【发布时间】:2021-01-13 03:05:49
【问题描述】:

我有这个 html 和 CSS

<div class="kalim"><img  src=""></div>

CSS

.kalim {display: inline-block;}

.kalim img {max-width: 800px;width: auto;max-height: 800px;}

此代码的问题是当浏览器调整大小时图像的宽度没有响应。如果我设置width:100%,那么高度超过 800 像素的人像图像就会变形。

是否有解决方法,使图像具有响应性并具有最大高度和最大宽度设置?

【问题讨论】:

    标签: html css


    【解决方案1】:

    您应该将宽度限制添加到外部元素而不是图像。外部元素的大小不会超过您的最大宽度和最大高度,但图像的宽度将始终为 100%。这样您的图像就会响应。

    html

     <div class="kalim"><img src=""></div>
    

    css

    .kalim {display: inline-block; max-width: 800px; max-height: 800px;}
    
    .kalim img {max-width: 100%; height:auto;}
    

    【讨论】:

      【解决方案2】:

      像 img-responsive 或 img-fluid bs4 的引导类 css

      <img src="chicago.jpg" style="max-width: 100%; height: auto; width: 800px"/>
      

      【讨论】:

      • 但我还需要保留 max-width:800px - 此解决方案不考虑这一点。
      【解决方案3】:

      我们可以使用 object-fit 来简化答案:

      .kalim img {max-width: 800px; max-height: 800px; object-fit: contain;}
      

      或

      .kalim img {max-width: 800px; max-height: 800px; object-fit: cover;}
      

      参考:https://www.w3schools.com/css/css3_object-fit.asp

      【讨论】:

        【解决方案4】:

        在 Bootstrap 4 中,您可以添加类 img-fluid 并设置 width 和 height 属性。

        <img class="img-fluid" src="https://source.unsplash.com/random/1600x1600" width="800" height="800">
        

        图片的大小可以是 1600x1600,但不会超过网页中 800x800 的大小。这也是响应式的。

        <html>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
        
        <img class="img-fluid" src="https://source.unsplash.com/random/1600x1600" width="800" height="800" alt="Image from unsplash">
        
        </html>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-02-04
          • 1970-01-01
          • 2015-10-20
          • 1970-01-01
          • 2019-05-04
          • 2020-11-11
          • 1970-01-01
          • 2013-09-23
          相关资源
          最近更新 更多