CSS的background-size:cover;效果不佳。

4
我有一个具有以下 CSS 样式的 #div 元素:
width: 413px;
height: 140px;
background-image: url("URL-TO-IMAGE");
background-color: #53A7E7;
background-size: cover;
background-position: center;
background-repeat: no-repeat;

结果如下所示:

banner

正如您可以在元素的左侧和底部看到的那样,有两条蓝线(颜色对应代码 #53A7E7)。
如果我删除样式 background-size: cover; ,这两条线就会消失,图片将覆盖整个元素表面。
有什么办法可以解决这个问题吗?
原始图像的尺寸为 1779x683 像素,但我希望它适用于任何图像大小。

#div {
    width: 413px;
    height: 140px;
    background-image: url("https://istack.dev59.com/SvWWN.webp");
    background-color: #53A7E7;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
<div id="div"></div>


1
请将您的代码发布在代码片段中。 - Dhaval Jardosh
1
请发布与此相应的 HTML。"works badly" 不是问题的很好描述。 - disinfor
我以前也遇到过类似的问题,虽然我认为这不是最好的解决方案,但对我来说还是有效的。我的做法是将宽度和高度设置为比视口的宽度/高度稍微大一些,例如 width:115vw; height:=110vh; - Progs
1个回答

5
不要同时使用background-colorbackground-size: cover,因为图像会覆盖颜色。如果你需要在background-size周围有一个覆盖的颜色,只需添加border即可。 background-size: cover是有效的。在您的示例中,我认为您需要display: inline-block

#div {
    width: 413px;
    height: 140px;
    background-image: url("https://istack.dev59.com/SvWWN.webp");
    border: 10px solid #53A7E7;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
<div id="div"></div>


不确定这是否回答了问题...可能我完全错过了问题,但似乎这些行是不需要的,这只是一个简单的渲染问题。 - Temani Afif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接