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?
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?
The background-image CSS property sets one or more background images on an element.
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.
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With