背景图像未显示在div中?

问题描述 投票:0回答:4

我有以下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');

html css
4个回答
1
投票

使用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%;
}

参见此working example


1
投票

这是因为您正在混合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>

确保您提供的路径上有真实的图像。


1
投票

我认为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;
}

0
投票
background-image: url('images/testImg.png');

将在加载CSS文件的文件夹中查找images文件夹。如果图像在另一个目录中,则应使用相对于根路径的路径(以/开头)

background-image: url('/images/testImg.png');
© www.soinside.com 2019 - 2024. All rights reserved.