div 中未显示背景图片

Background image is not showing up in div

我已经尝试了所有方法,但无法弄清楚为什么我无法为此显示背景图片 div。

**Here is the code:**

body {
  margin: 0px;
  padding: 0px;
}

#top {
  background-image: url(../IMG/PINS.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
<html>

<head>
  <title>TEST BCKGRND IMAGE</title>
  <link rel="stylesheet" type="text/css" href="CSS/style.css">
</head>

<body>
  <div id="top">


  </div>
</body>

</html>

文件结构设置如下:我有一个名为 TEST_SITE 的主文件夹,在该文件夹内有一个文件夹 CSS 和一个名为 IMG 的图像文件夹。

我一辈子都弄不明白为什么背景图片不显示。

如果有人能告诉我可能出了什么问题,我将不胜感激。

谢谢。

您需要根据 #top 设置高度和宽度值,并像我的回答一样使用 background-position:center center; background-repeat:no-repeat;:例如

#top{
   width:500px;
   height:500px;
   background-image: url(YOUR IMAGE PATH); 
   background-repeat:no-repeat;
   background-position:center center;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

或者你也可以这样做:

#top{ 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   background:url(YOUR IMAGE PATH) no-repeat fixed center; 
   width:500px;height:500px;
 }

因为你的div是空的。如果您向其中添加内容,那么您将看到背景。您还可以使用 CSS.

设置高度或添加填充
<div id="top">
 <p>A large amount of text here</p>
</div>  

#top{
 height:400px;
 background-image: url(yourimagehere); 
 background-repeat:no-repeat;
 background-position:center center;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;
}

#top{
 padding: 25px 0;
 background-image: url(yourimagehere); 
 background-repeat:no-repeat;
 background-position:center center;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
 background-size: cover;
}

设置 #top div 的高度很重要:如果你设置宽度,然后设置高度为自动,那么背景仍然不会显示,因为里面没有任何东西div 放置背景。但是,如果您通过在 css 中设置一个高度来强制设置高度,那么背景将会显示。 您为您的路径提供的代码不正确,因为 background-image 只需要一个图像路径(而不是其他任何东西),而您提供的代码适用于 background

看我的fiddle