CSS Background-Image refuses to display in ASP.Net MVC

This is what I had to do:

background-image: url('@Url.Content("~/images/foo.png")')

In my case I had to back out to the root and include a path to the Content directory.

So even if my directory structure looked like:

-Content
--css
---site.css
--img
---someImg.png

I couldn't do

background-image: url(../img/someImg.png)

I had to do:

background-image: url(../../Content/img/someImg.png)

This worked locally in debug mode (no minification) and deployed to AWS (with minification) correctly.

Also, don't forget if you're using Bundle minification and you use @import in your CSS to still include the asset in the bundle. For example:

main.css
@import url(../../Content/css/some.css)

Be sure to include some.css in your bundle:

 bundles.Add(new StyleBundle("~/Content/global").Include(
                 "~/Content/css/some.css",
                 "~/Content/css/main.css"));

No need to do this if you're using LESS or SASS bundlers as the handler knows how to find the files and include them (that's the point!); however, if you're doing it as a straight CSS import, the bundler won't know to include it when it minifies.

Hope this helps someone!


If you use bundles and have the directory structure like :

-Content
--lightbox
---css
----lightbox.css
---imgages
----close.png

then you can make a separate bundle for content in subdirectories by defining the bundle in that subdirectory:

bundles.Add(new StyleBundle("~/Content/lightbox/css/bundle")
                .Include("~/Content/lightbox/css/lightbox.css"));


background-image: url(../images/close.png); 

The url inside a CSS file is relative to the location of the CSS file.

So if we suppose that you have ~/content/foo.css and you want to include ~/images/foo.png here's how to reference it inside foo.css:

background-image: url(../images/foo.png); 

Don't use any ~ inside a CSS file. It has no meaning.

So in your case if the CSS file is ~/Content/Site.css and you want to reference ~/Content/Images/Designs.png the correct syntax is:

background-image: url(images/designs.png); 

If this doesn't work for you there might be different causes:

  • The image doesn't exist at that location
  • You didn't specify width and height to the containing element so you don't see the image

What I would recommend you is to use FireBug and inspect the corresopnding DOM element to see exactly what styles and images are applied to it.