Anton Putov
Anton Putov

Reputation: 1981

background-image in MVC4 not work

I am using basic template for mvc 4.I want set background image for my div element.My stylesheet located in "~/Content" directory.Here is part of my .cshtml file where I am trying direct specify image without css:

        <div id="add_image" class ="image_bar" style="background-image:url(add.jpg)" ></div>

Here is my css:

#add_image {
    background-image:url('~/add.jpg');
}

#add_image:hover {
    background-image:url('~/addhover.jpg');
}
.image_bar {
    width:40px;
    height:40px;
}

Neither css neither direct "styling" not works - whats wrong? Thanks.

Upvotes: 1

Views: 11174

Answers (4)

Codeone
Codeone

Reputation: 1201

try this **example -

background-image:url('../img/home_bg.jpg');**

background-image:url('../**ImageFolderName**/add.jpg');

Upvotes: 0

user3073441
user3073441

Reputation: 1

try with

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

Upvotes: 0

hrkoder
hrkoder

Reputation: 1

Instead of

background-image:url('~/add.jpg');

try using

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

Upvotes: 0

Tommy
Tommy

Reputation: 39807

In your second example, you are using the '~/' moniker, this is a .NET thing that instructs the code to look at the root of the site. Since the .NET engine does not process your CSS file, the '~/' has no effect and probably makes a really ugly HTTP request to the server.

Since you have your CSS in your Content directory, one solution is to create a sub directory in your Content called 'images'. Store any and all of your CSS images in that folder. Then, from your CSS file, you can call and reference images in that file as such:

#add_image {
    background-image:url('images/add.jpg');
}

#add_image:hover {
    background-image:url('images/addhover.jpg');
}

This is assuming a directory structure like so:

  • Content
    • images
      • add.jpg
      • addhover.jpg
    • site.css

Though I am not a designer, I believe that CSS will look for images relative to the location of the CSS file and not the root of the web application like HTML. Additionally, if you stored images in the same directory as your CSS file, then you should be able to call those images without the 'images/' prefix. However, most like to keep resources separate.

Upvotes: 6

Related Questions