CSS Background-Image Refuses to Display in ASP.NET MVC

CSS Background-Image refuses to display in ASP.Net MVC

The url inside a CSS file is relative to the location of the CSS file.

So if we suppose that you have ~/content/foo.css and you want to include ~/images/foo.png here's how to reference it inside foo.css:

background-image: url(../images/foo.png); 

Don't use any ~ inside a CSS file. It has no meaning.

So in your case if the CSS file is ~/Content/Site.css and you want to reference ~/Content/Images/Designs.png the correct syntax is:

background-image: url(images/designs.png); 

If this doesn't work for you there might be different causes:

  • The image doesn't exist at that location
  • You didn't specify width and height to the containing element so you don't see the image

What I would recommend you is to use FireBug and inspect the corresopnding DOM element to see exactly what styles and images are applied to it.

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

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.

Background image not showing in ASP.NET Core

I'll assume the snippet above is from an MVC view. When you're using the wwwroot folder, that represents the static content root against which other things can reference (unless you've explicitly changed that). So, the 'wwwroot/images/bkimage.jpg' would just be the root-relative path '/images/bkimage.jpg' off that.

Try the following:

background-image: url('/images/bkimage.jpg'); 

ASP.NET MVC background image

Don't use an absolute path. Use a relative path.

if your css file is located here for instance (from the root of your site):
/Styles/Site.css

then your CSS should be:

body {
padding-top: 50px;
padding-bottom: 20px;
background-image:url(Images/background.jpg)
}

so, you're saying from where your css file is (/Styles) your image file is a sub-directory of this (/Styles/Images/[the-filename-for-your-image]).

Also, not the use of / rather than \ in your image path

CSS Background image not displaying in ActionLink in MVC4

Are you sure that the pathing is correct? The URL you specify in CSS is relative to that CSS file.

CssFolder

       styles.css

ImagesFolder

       image.png

Alternatively you could use url.content to ensure you're taking the right path:

@Html.ActionLink(
" ",
"Index",
"Home",
new {
style = "background: url('" + Url.Content("~/Images/yourimage.png") + "') no-repeat center right; display:block; height:84px; width:585px;"
}
)


Related Topics



Leave a reply



Submit