Back

How to set image path in 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.

Resolve image path with stylebundle

If you open the browser debugger, you can see that the css file has been loaded with Status 200.

Resolve image path with stylebundle

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.

site.css
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.

Resolve image path with stylebundle

However, the browser will give the 404 error because it could not find the image file.

Resolve image path with stylebundle

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.

Resolve image path with stylebundle

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.

Example: Specify CssRewriteUrlTransform

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.

Resolve image path with stylebundle

As you can see in the above figure, the image is loaded using an absolute path from the root folder.