为什么我无法设置背景图片?

时间:2017-05-16 08:29:13

标签: html css background-image

我知道这是一个重复的问题,但我的代码存在问题。 我搜索了stackoverflow和w3schools进行背景图像设置 并编写了两个网站上的代码,但我仍然遇到以下代码的问题。

body {
  background-image: url("C:\Users\mehra\Desktop\Male-Fitness-Models-BAck.jpg");
}

body{  background-image: url("Male-Fitness-Models-BAck.jpg");  }

以上是我用于设置背景的代码,但它们都不起作用。

HTML picture

4 个答案:

答案 0 :(得分:2)

如果背景图像文件位置正确,则可能需要在背景图像的容器中添加高度和宽度。

body {
  height: 500px;
  width: 500px;
  background-image: url("C:\Users\mehra\Desktop\Male-Fitness-Models-BAck.jpg");
}

答案 1 :(得分:1)

body 
{
background : cover;
background: url("http://quizdoo.com/wp-content/uploads/qc-images/58d2957b47354.jpg"); 
}
<body>
</body>

Add background size to make it visible

body 
{
background: cover;
background-image: url("C:\Users\mehra\Desktop\Male-Fitness-Models-BAck.jpg"); 
}

答案 2 :(得分:1)

There are a few things to investigate to ensure it always works:

1) Using the project absolute path:

ensure you have FollowSymLinks in your vhosts enabled, that way you can use / in the src to call the image.

e.g. <img src="/images/dog.png" />

2) Make sure the image exists

copy and paste the src that's displayed in the browser (inspect with firebug, or view-page source to get the link) into the url bar and see what it returns - if it's a 404 then it doesn't exist on the path you gave, if it's 403 the path might be set to really strict permissions (755 on directories and 644 for files is recommended) and you might have to tweak your vhosts file to allow people to view the content, but not access the file tree.

3) If the image does exist, there is no message (other than 200) and you're using the path correctly - then it's probably because the div is empty. A background on a div with no content will result in empty space, because the background is stretching itself over 0 pixels. Add a min-height and min-width rule to your css or use &nbsp; inside the div:

CSS:

div {
    background: url('/images/dog.png');
    min-height: 50px;
    min-width:  50px;
}

HTML:

<div>&nbsp;</div>

4) Use a proper folder structure

by using a file tree that makes sense, it makes resources easier to manage. Hosting every file in the DOCUMENT_ROOT is messy, I'd recommend the below structure:

|--index.html
|----images/
|----css/
|----js/

that's a basic structure, then you can add more folders based on area e.g.

|--index.html
|----[area]/
|----images/
|----css/
|----js/

答案 3 :(得分:0)

如果您使用的是 PC 保存的图像路径,请确保将 \ 替换为 /,它会起作用。

示例:

background-image:url("C:/Users/foldername/Desktop/images/City_Landscape_Background.jpg");