How to set image path with StyleBundle
In this article, you will learn how to resolve an absolute path in a css file.
We learned in the MVC tutorial that the Include()
method of the Bundle class accepts a filename with a virtual path.
If you open the browser debugger, you can see that the css file has been loaded with Status 200.
However, if the site.css contains images with an absolute path, then the images will not load. For example, our following site.css contains footer style as shown below.
footer
{
background:url(../images/border_btm.png) top repeat-x;
padding:15px;
color:#618eac;
margin-top:15px;
}
The above footer style references the background image, which is in the separate images folder.
However, the browser will give the 404 error because it could not find the image file.
The browser will consider the virtual path for any path given in the css file. It will try to load the image from hosting server.
Solution:
If you use an absolute path in your css for images then you can specify the transformation class CssRewriteUrlTransform.
The CssRewriteUrlTransform
class rewrites urls to absolute paths.
bundles.Add(new StyleBundle("~/bundles/css").Include(
"~/Content/css/site.css",
new CssRewriteUrlTransform()
));
Now, the image path in the css file will be transformed into an absolute path.
As you can see in the above figure, the image is loaded using an absolute path from the root folder.