NibblyPig
NibblyPig

Reputation: 52942

CSS url path incorrect with MVC 3

I have this:

body {
    background-image: url("Images/Background.jpg");
}

But the url it generates is incorrect no matter what variation I use.

When I run my website, the url is localhost/MYSITE as it's plonking it on a local IIS server (not iisexpress).

The image is stored in a folder called Images on the root of the application.

if I inspect the element this is what I get:

background-image: url("Images/Background.jpg");

gives

url("http://localhost/MYSITE/Styles/Images/Background.jpg")

I don't know where the Styles comes from.

background-image: url("/Images/Background.jpg");

gives

url("/Images/Background.jpg")

Which is wrong since it needs to be MYSITE/Images.

background-image: url("~/Images/Background.jpg");

gives

url("http://localhost/MYSITE/Styles/~/Images/Background.jpg")

Styles is the location of the LESS file so I guess that is sorta why?

background-image: url("~/../Images/Background.jpg");

gives

url("http://localhost/MYSITE/Styles/Images/Background.jpg")

What is going on?! Why does it keep doing these weird things?

When I deploy to live it will no longer be IP/MYSITE it will be mysite.mydomain.com so I have to get the relative pathing correct.

Upvotes: 1

Views: 698

Answers (1)

Ravi Kumar
Ravi Kumar

Reputation: 993

If you give url of image in css it path start right from the folder where your css is so if your css file is inside Styles folder and you give background-image url as

url("/Images/Background.jpg");

localhost/MYSITE/Styles/Images/Background.jpg

because your folder structure is like this

Root
  Styles
  Images

so if you want to point some image in the Images folder from your css file in Styles folder you should write like this

url("../Images/Background.jpg");

It means go to the parent folder that is Root and then Images and then Background.jpg

Upvotes: 2

Related Questions