javascript - CSS 裁剪图像以适应屏幕宽度,同时保持图像的原始高度

标签 javascript html css

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

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

我制作了宽度为 6000px 的图像,以便适合所有屏幕。

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

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;
}

最佳答案

试试这个:

.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;
}

关于javascript - CSS 裁剪图像以适应屏幕宽度,同时保持图像的原始高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46490242/

相关文章:

javascript - Angular 需要 Zone.js polyfill。使用系统 js 我正面临这个问题

javascript - 无法在 Angular 7 HTTP 拦截器中捕获 401 状态代码

javascript - boolean 值不是函数

html - 在一个 div 中居中一个 div。里面的div一定要小于父div。 Bootstrap 4

javascript - 最有可能的是如果功能不起作用

html - 如何在不更改按钮大小的情况下将文本包装在 Bootstrap 按钮内?

html - 滚动时标题中的内容可见

css - 字体渲染和 :before in firefox

html - 带有CSS的中心输入框

html - Internet Explorer 中的模糊文本