Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC cannot display image using background-url in css - uses bundling

I have an MVC4 project which has the following structure:

/Content/css/sprites/topbar.css

/Content/images/topbar.png

In the css file I am trying to reference the image by using:

background: url('../../images/topbar.png')

But the image is not displayed. If I change it so that the image is located in:

/Content/css/sprites/topbar.png

And change the css to be:

background: url('content/css/sprites/topbar.png')

it works, but this breaks my project structure.

Any ideas?

EDIT

I didn't mention something else as I didn't think it was relevant, however it appears to affect this!

I use @System.Web.Optimization.Styles.Render("~/MainStyles") to bundle and minify the css, but if I take that step out, then it works as I would expect. How would I get it all to work with my project structure and using the bundling?

like image 552
eyeballpaul Avatar asked Sep 10 '12 12:09

eyeballpaul


People also ask

What CSS property sets one or more background images on an element?

The background-image CSS property sets one or more background images on an element.

How does background-image work CSS?

The background-image CSS property allows you to then place the image behind any HTML element you wish. This could either be the whole page (by using the body selector in CSS which targets the <body> element in our HTML), or just a standalone specific part of the page such as a section element like in the example below.


2 Answers

Don't know if anyone else was having this problem. But you CAN use relative paths in your css. The key is registering the bundle with a virtual path to the same folder where your actuall css will reside. This way MVC Will request the bundled css from a handler in that path.

Try changing your bundle registration to:

bundles.Add(new StyleBundle("~/Content/css/sprites/topbar")
              .Include("~/Content/css/sprites/topbar.css")
            );

Then in your view @Script.Render("/Content/css/sprites/topbar")

Mvc will request your complied css bundle from /Content/css/sprites/topbar?{some-crazy-token-thing}

like image 182
tfx_wse2012 Avatar answered Oct 17 '22 09:10

tfx_wse2012


I found out what the issue was.

It was indeed the bundling and minification used in MVC. When the css was looking for images, it was looking in the folder that my bundle was pointing to as the current folder, rather than the folder the css file is located in.

like image 5
eyeballpaul Avatar answered Oct 17 '22 10:10

eyeballpaul