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

前端 未结 4 505
花落未央
花落未央 2020-12-20 22:07

I have an MVC4 project which has the following structure:

/Content/css/sprites/topbar.css

/Content/images/topbar.png

In the c

相关标签:
4条回答
  • 2020-12-20 22:37

    I recommend storing CSS-referenced images in the same folder as, or a subfolder of the directory holding the CSS file itself, so you can use minimally-long relative paths in your CSS file.

    If your application always resides in the root of the website, you could use root-relative paths (e.g background-image: url("/content/images/toopbar.jpg"); )

    Hmm, but then "../images/topbar.png" should also work. Have you tried that?

    0 讨论(0)
  • 2020-12-20 22:41

    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}

    0 讨论(0)
  • 2020-12-20 22:51

    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.

    0 讨论(0)
  • 2020-12-20 22:58

    Try using:

    .social ul li a.blog { background: url(@Url.Content("~/Content/img/houseIcon.png")) no-repeat left top; }
    

    For using razor in CSS, see this http://www.codeproject.com/Articles/171695/Dynamic-CSS-using-Razor-Engine

    0 讨论(0)
提交回复
热议问题