html - 在图像标签中复制 background-img 属性

标签 html css sass

我正在处理一个响应式页面,并且有一个大背景图像,无论用户使用什么尺寸的设备,我都希望它保持比例。当我使用 img为此它的标记延伸到屏幕底部之外,所以我使用 background-img属性代替。这是可行的,但我开始使用 img标记,无法复制与 background-img 相同的行为.

Based on this SO Post我相信我应该使用 img 来实现相同的效果或 background-img

根据我的阅读,我似乎应该能够使用其中任何一个并为用户创造相同的体验,所以很想知道如何复制 background-img将下面代码中的属性添加到我的代码中 img标签。

请看下面的代码。

随着 background-image属性集。这按我喜欢的方式工作。

HTML

<div id="container">
    <div class="main-image">
    </div>
</div>

CSS

html, body {
    width: 100%;
    margin: 0;
}
.main-image {
    background: url(http://i2.cdn.turner.com/cnnnext/dam/assets/151009172735-02-tbt-bob-dylan-restricted-super-169.jpg) center center no-repeat;
    background-size: cover;
    max-height: 90%;
 }

<img>属性。需要做什么来复制与上面的 css 相同的行为?我试过玩弄所有属性,但无法弄清楚这一点。

HTML

<div id="container">
    <div class="main-image">
        <img src="http://i2.cdn.turner.com/cnnnext/dam/assets/151009172735-02-tbt-bob-dylan-restricted-super-169.jpg">
    </div>
</div>

CSS

html, body {
    width: 100%;
    margin: 0;
}

.main-image {
    width: 100%;
    max-height: 90%;
 }

img { 
    width: 100%;
 }

最佳答案

您可以尝试在 img 上使用 object-fit: cover;

关于html - 在图像标签中复制 background-img 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39488110/

相关文章:

html - 跨浏览器日期选择器组件(与移动和桌面浏览器兼容)和 Bootstrap

Javascript - 添加顶部固定条并将所有其他元素向下推

html - 内衬和造型元素

html - 我的页脚已经移动到页面的一半位置,我有不必要的滚动

css - 本地机器上 SCSS 函数的返回值与 codepen 上的返回值不同

angular - i18n 编译因 Sass 失败 - 找不到资源文件

javascript - 将一些 HTML 从一个地方传送到另一个地方

javascript - Uncaught ReferenceError : phone is not defined javascript error

html - 如何根据 child 的内容使父 div 拉伸(stretch)?

css - compass : Compiling Style Sheets Changes "Black" to "#000"