我有以下div:
<div class="soundscapeImgDiv"> </div>
在CSS中,我尝试像这样设置背景:
.soundscapeImgDiv {
/* background-color: white; */
background-image:url('images/testImg.png') no-repeat;
background-size: 100%;
width: 280px;
height: 85%;
margin-left: 10px;
margin-top: 12px;
border-radius: 12px;
}
但是当我不显示图像时。如果我只留下颜色,则会显示框。
如何解决此问题并使图像显示为背景?
更新:我目前正在得到
获取文件:///images/testImg.png净额:: ERR_FILE_NOT_FOUND
在终端中。对于background-image:url('/images/testImg.png');
使用background-repeat
属性
div.soundscapeImgDiv {
/* background-color: white; */
background-image: url("images/testImg.png");
background-size: 100%;
background-repeat: no-repeat;
width: 280px;
height: 85%;
margin-left: 10px;
margin-top: 12px;
border-radius: 12px;
}
html, body {
height: 100%;
}
这是因为您正在混合background-image
属性和background repeat
属性。
如果要在一行中同时声明两者,请使用background
属性:
.soundscapeImgDiv {
/* background-color: white; */
background: url('https://picsum.photos/150/450') no-repeat;
background-size: 100%;
width: 280px;
height: 85%;
margin-left: 10px;
margin-top: 12px;
border-radius: 12px;
}
<div class="soundscapeImgDiv"> </div>
确保您提供的路径上有真实的图像。
我认为no-repeat语句弄乱了代码,请尝试删除no-repeat或使用:-
.soundscapeImgDiv {
/* background-color: white; */
background-image:url('images/testImg.png');
background-size: 100%;
background-repeat:no-repeat;
width: 280px;
height: 85%;
margin-left: 10px;
margin-top: 12px;
border-radius: 12px;
}
background-image: url('images/testImg.png');
将在加载CSS文件的文件夹中查找images文件夹。如果图像在另一个目录中,则应使用相对于根路径的路径(以/开头)
background-image: url('/images/testImg.png');