【问题标题】:CSS crop image to fit screen width while keeping the original height of the imageCSS裁剪图像以适应屏幕宽度,同时保持图像的原始高度
【发布时间】:2018-03-11 10:37:22
【问题描述】:

我正在尝试在main-content 的末尾显示一个图像(6000 像素宽,300 像素高),例如背景图像。图片应该适合屏幕的宽度,但要保持原点高度。

换句话说,总是在中心裁剪图像,而 x-crop 的宽度是屏幕宽度大小,而高度裁剪是图像的原始高度。

我已经制作了 6000 像素宽度的图像,这样我就可以适应所有的屏幕了。

下面的代码并没有像预期的那样工作,它只是显示原始的img,同时缩放高度以保持相对于屏幕宽度的纵横比。

newnewwaves.svg : http://svgshare.com/i/3DT.svg

我希望如何显示:https://ibb.co/e80Ddw

HTML:

<div class="main-content">
       ...content
        <div id="header-waves">
            <img src="/assets/images/newnewwaves.svg" alt="">
        </div>
 </div>

CSS:

.main-content {
   position: relative;
}
#header-waves {
   position: absolute;
   left: 0;
   bottom: 0;
}
#header-waves img {
  width: 100%;
  height: auto;
  display: block;
}

【问题讨论】:

  • 快速提问这是一张真实的图片,还是更多的重复背景?
  • 这是一个实际的图像(waves),图像意图用作背景。在元素的末尾
  • 为什么不用 CSS 将其添加为背景图片??
  • 因为我不认为我可以在需要时使用剪辑路径,我想出于我的目的,我已经使用基于去抖窗口调整大小事件的 javascript 操作内联剪辑路径
  • 用户溢出:您的 img 的隐藏属性?

标签: javascript html css


【解决方案1】:

试试这个:

.img-class {

    width: 100%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    object-fit: cover; 
}

这将有助于通过限制宽度和裁剪图像使其居中来保持纵横比。

如果这不起作用,请试试这个:

.img-class {
  width: 100%;
  height: 400px; /* Set your fixed Limit */
  background-size: cover;
}

【讨论】:

    【解决方案2】:

    你可以使用 background: url(...) 来做,就像例子..

    .main-content
    {
      background: url('http://via.placeholder.com/6000x300');
      background-size: auto 100%;
      width:100%;
      height:300px;
    }
    <div class="main-content">
           ...content
     </div>

    【讨论】:

    • 我不想设置 .main-content 的高度,因为它是一个 flex 元素,并且它的高度是相对于它的兄弟元素复制的
    【解决方案3】:

    您可以将图像放在带有width: 100% 的容器中,并将溢出属性设置为隐藏。

    使用flexbox 使图像在此容器中居中。

    请注意,如果您将其设为全屏并调整浏览器大小,则此 sn-p 更易于测试...

    #header-waves {
      width: 100%;
      overflow: hidden;
      display: flex;
      justify-content: center;
    }
    <div class="main-content">
      <div id="header-waves">
        <img src="https://placehold.it/6000x300" alt="">
      </div>
    </div>

    【讨论】:

    • 不按预期工作将附加图像,使其更清晰
    • @GeorgiAntonov 好的,仅基于图像很难进一步提供帮助。您链接的网站是动态计算高度的,比 sn-p 更复杂。
    • 您好,谢谢,通过将 object-fit:cover; 应用于 img 元素,我能够使其适用于我的用例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2017-12-19
    • 2021-10-06
    • 1970-01-01
    相关资源
    最近更新 更多