html - 如何使 img 的行为与背景图像相同?

标签 html css

我使用图像作为背景图像,background-image: url() ,我也使用放置在 <img src=""> 内的图像

看起来 src 图片的高度比背景图片的高度要短。
如果我将源图像的高度设置为等于背景图像的高度,则源图像将会受到干扰。

我应该设置什么CSS属性才能使src图像与背景图像具有相同的高度,但又不会干扰src图像?请注意:我只需要在 src 图像中进行调整,而不是在背景图像中进行调整。

请看看我的sample in jsfiddle

HTML

<p>
This is background image
</p>

<div class="imageBG">

</div>


<p>
Below is a front image.  Its height looks like less than the height in background image.
</p>
<div>
    <img src="https://library.danahall.org/wp-content/uploads/2019/04/2560px-Bufo_periglenes2.jpg">
</div>

CSS

.imageBG {
  background-image: url("https://library.danahall.org/wp-content/uploads/2019/04/2560px-Bufo_periglenes2.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  height: 353px;
}

img {
  width: 100%;
  /* height: 353px; */
}

请注意:因为我使用的图像很长,所以我必须为img设置width: 100%。如果我不设置,导航栏将显示在浏览器底部。

最佳答案

考虑object-fitobject-position

.imageBG {
  background-image: url("https://library.danahall.org/wp-content/uploads/2019/04/2560px-Bufo_periglenes2.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  height: 353px;
}

img {
  width: 100%;
  height: 353px;
  object-fit:cover;
  object-position:center;
  display:block; /*to make it behave as div and avoir whitespace issue*/
}
<p>
This is background image
</p>

<div class="imageBG">

</div>


<p>
Below is a front image.  Its height looks like less than the height in background image.
</p>
<div>
    <img src="https://library.danahall.org/wp-content/uploads/2019/04/2560px-Bufo_periglenes2.jpg">
</div>

相关更多详情:Object-fit On A Canvas Element

关于html - 如何使 img 的行为与背景图像相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669146/

相关文章:

JavaScript:使用 onchange 使用下拉菜单过滤数据

python - 为什么我的 Flask 应用程序不能连接到我的 CSS 文件?

css - 旋转卡在鼠标指针所在的位置

html - 段落文本不会换行到下一行

javascript - 使用 getDate JavaScript 计算一个月中的天数

JavaScript 待办事项列表划掉所有其他元素

html - 图像未随脚本一起加载

javascript - 使用 Tab 键进行页面导航时滚动到表单元素上的错误消息

asp.net - 使用 CSS 对齐表中的 ASP 控件

html - CSS 水平紧贴 n 个元素