Change relative URL references to CSS files when bundled


from customer: Ido Ran

I've come acros a problem when using the great new ASP.NET bundle feature.
There is a problem when using urls such as reference to background images inside CSS that is bundled because the virtual path to the bundle is where the images are searched for but they are not always there.

Check out this StackOverflow questions which describe both the problem and the solution.
The problem is that the bundle feature does not make it obvious when using it.

Closed Apr 17, 2013 at 9:33 PM by howarddierking


asbjornu wrote Oct 26, 2012 at 11:58 AM

This bit me just now and seeing how the CSS is parsed and compacted, it should be a small job finding all url() functions and replacing their values with something that resolves after bundling. This could also bring support for using ~/ in the CSS file, which would be awesome.

HaoK wrote Mar 13, 2013 at 4:59 PM

This is fixed by using the new Include overload that takes a per item transform:
                bundles.Add(new StyleBundle("~/bundles/css")
                    .Include("~/Styles/image.css", new CssRewriteUrlTransform())
                    .Include("~/Styles/nested/image2.css", new CssRewriteUrlTransform()));

Adhooo wrote Mar 14, 2013 at 4:22 PM

I don't get CssRewriteUrlTransform to work as I expect it to.
Dim masterCssBundle As New StyleBundle("~/bundles/styles/common")
masterCssBundle.Include("~/Content/Styles/UserControls/Menu/simpleMenuList.css", New CssRewriteUrlTransform())
background-image: url(../../../../images/ConfigmenuInactive.png);
Resulting ~/bundles/styles/common:
background-image: url(/images/ConfigmenuInactive.png);
I would expect the resulting css to be:
background-image: url(../../images/ConfigmenuInactive.png);
What am I doing wrong?

HaoK wrote Mar 17, 2013 at 5:58 PM

Looking at this issue, I think the behavior is correct, the transform resolves the url to the absolute url, not rebasing it against the new bundle url.

Adhooo wrote Mar 17, 2013 at 7:16 PM

How do you suggest I change my code to make it work?

ericbock wrote Apr 1, 2013 at 6:24 PM

HaoK, resolving the url to an absolute path won't work when the site runs in a virtual directory since the virtual directory isn't included in the path, right?

rliberoff wrote Apr 3, 2013 at 11:46 AM

It is not working. My Web Forms Application is in a Virtual Directory and the relative image path in the CSS file is being substituted by an absolute path that is not real.

Original path = url('../Images/sprite.png')

Transformed path = url('Images/sprite.png')