【问题标题】:Resize Images, keeping ratio, html?调整图像大小,保持比例,html?
【发布时间】:2017-06-14 18:59:21
【问题描述】:

我正在尝试调整背景图片的大小以适合 div。我遇到的问题是我希望图像适合 div 的高度并保持比例。例如,我有一个 div,我不希望它进一步增加屏幕的宽度(以防止出现滚动条),并且我想要使用的图像是 1024px X 400px。如果我尝试适应图像的高度,它也会强制宽度适应并且它会失去比例。我不在乎图像的某些部分是否未显示。事实上,这就是我想要做的。
我需要使用哪些标签? HTML5 或 CSS

【问题讨论】:

    标签: html css image


    【解决方案1】:

    使用 CSS background-size: cover; 填充 <div>background-size: auto 100%; 如果您只想匹配高度而不关心边是否溢出或溢出:

    html,
    body {
      position: relative;
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }
    
    div {
      background-image: url(https://placebear.com/1024/400.jpg);
      display: inline-block;
      background-repeat: no-repeat;
      border: 1px solid black;
    }
    
    .cover {
      background-size: cover;
    }
    
    .center {
      background-position: center;
    }
    
    .height {
      background-size: auto 100%;
    }
    <h1>Unstyled</h1>
    <div style="width: 50px; height: 200px"></div>
    <div style="width: 200px; height: 50px"></div>
    <div style="width: 125px; height: 125px"></div>
    
    <h1>Un-centered</h1>
    <h2>Cover</h2>
    <div class="cover" style="width: 50px; height: 200px"></div>
    <div class="cover" style="width: 200px; height: 50px"></div>
    <div class="cover" style="width: 125px; height: 125px"></div>
    
    <h2>100% Height</h2>
    <div class="height" style="width: 50px; height: 200px"></div>
    <div class="height" style="width: 200px; height: 50px"></div>
    <div class="height" style="width: 125px; height: 125px"></div>
    
    <h1>Centered</h1>
    <h2>Cover</h2>
    <div class="cover center" style="width: 50px; height: 200px"></div>
    <div class="cover center" style="width: 200px; height: 50px"></div>
    <div class="cover center" style="width: 125px; height: 125px"></div>
    
    <h2>100% Height</h2>
    <div class="height center" style="width: 50px; height: 200px"></div>
    <div class="height center" style="width: 200px; height: 50px"></div>
    <div class="height center" style="width: 125px; height: 125px"></div>

    此外,如果您想裁剪图像,请使用background-position: center;,使中心始终是焦点,而不是左上角。

    【讨论】:

      【解决方案2】:

      如果你可以稍微降低你的比率阈值,你也可以使用:

      img {
        width: 100vw;
        height: 100vh;
        max-width: 100%;
        max-height: 100%;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-05-12
        • 1970-01-01
        • 2015-04-09
        • 2017-08-24
        • 2011-04-27
        • 2013-06-26
        • 2012-04-15
        相关资源
        最近更新 更多