【问题标题】:Background image is not showing up in div背景图像未显示在 div 中
【发布时间】:2019-02-11 02:03:00
【问题描述】:
我已经尝试了所有方法,但无法弄清楚为什么我无法让背景图像显示在这个 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 的图像文件夹。
我终其一生都无法弄清楚为什么背景图片没有显示出来。
如果有人能告诉我可能出了什么问题,我将不胜感激。
谢谢。
【问题讨论】:
标签:
html
css
image
background
background-image
【解决方案1】:
设置#top div 的高度很重要:如果您设置宽度,然后将高度设置为自动,那么背景仍然不会显示,因为 div 内没有任何东西可以放置背景。但是,如果您通过在 css 中设置一个来强制高度,那么背景将显示。
您为路径提供的代码不正确,因为background-image 只需要图像的路径(没有别的),而您提供的代码适合background。
见我的fiddle
【解决方案2】:
您需要从#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;
}
【解决方案3】:
这是因为你的 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;
}