我使用图像作为背景图像,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-fit
和object-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>
关于html - 如何使 img 的行为与背景图像相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669146/