A.S.J
A.S.J

Reputation: 637

How to add local file as background in CSS?

Path for my HTML-file: C:\Users\Name\Documents\Coding\Battleship\index.html
Path for the picture: C:\Users\Name\Documents\Coding\Battleship\Water.jpg

I tried to add it as follows:

body {
    background-image: url("file://C:\Users\Name\Documents\Coding\Battleship\Water.jpg") no-repeat center center;
    background-size: cover;
}

However, it is not working. Does anyone know how to solve this issue?

Upvotes: 1

Views: 14600

Answers (4)

Winnies World
Winnies World

Reputation: 11

Not sure if this is too late to answer but I think the problem is very simple. You have done the right thing with the URL, here is the tricky bit: the link to your URL has a backward slash(there's no need for using CSS to correct this) ie: Yours: Path for my HTML-

file: C:\Users\Name\Documents\Coding\Battleship\index.html

Correct Answer: should have a forward slash Path for my HTML-file:

 C:/Users/Name/Documents/Coding/Battleship/index.html

Upvotes: 1

Abdulla Nilam
Abdulla Nilam

Reputation: 38652

You can't do like this

background-image: url("file://C:\Users\Name\Documents\Coding\Battleship\Water.jpg") no-repeat center center;

You can place the image is project root(or subfolder) and use as below

Assume your project folder is Battleship

If you place Water.jpg in root(as below)

Battleship
-index.html
-Water.jpg

then use this

body {
    background-image: url("./Water.jpg") no-repeat center center;
    background-size: cover;
}

If you place Water.jpg in subfolder (as below)

Battleship
-index.html
-images
    -Water.jpg

then use this

body {
    background-image: url("./images/Water.jpg") no-repeat center center;
    background-size: cover;
}

Check this w3schools.com source

Upvotes: 5

Naren Murali
Naren Murali

Reputation: 57941

Please refer the below tested code.

The problem was you were using background-image which only accepts one parameter, you were supposed to use background which is a shorthand for writing all the background properties into one.

Refer: CSS background [last section]

You need to change the below CSS

body {
        background: url("Water.jpg") no-repeat center center;
        background-size: cover;
    }

Code example:

html, body{
  width:100%;
  height:100%;
  margin:0px;
}
body {
    background: url("http://lorempixel.com/400/200/") no-repeat center center;
    background-size: cover;
}
<html>
<body>
</body>
</html>

Upvotes: 2

Harden Rahul
Harden Rahul

Reputation: 948

just make a folder & put both files into it and link your image path simply.

Upvotes: 0

Related Questions