简体   繁体   中英

Local CSS background-image not displaying

I'm trying to display a local background-image in CSS. It's in the same folder as index.html and it's not displaying.

    .image {
        width:100px;
        background-image: url('PIC1.jpg');
    }

Any help is appreciated.

Resources specified in CSS are resolved relative to the path of the CSS file, not the page referencing the CSS file. PIC1.jpg must be located in the same directory/folder as the CSS file itself.

There is no way in CSS to do what you think it does - and that's a good thing, because I can't think of any possible use-case. Imagine having these pages all referencing style.css :

/index.html
/products/fish.html
/user/account/orderHistory

...if style.css referenced "foo.jpg" then foo.jpg would have to be replicated at /foo.jpg , /products/foo.jpg and /user/account/foo.jpg .

I can think of 3 possible problems. First, the image path. for example if this is your image's real path: D:\\Projects\\MyProject\\Content\\Images\\PIC1.jpg

you should do this in your code:

background-image: url('~\Content\Images\PIC1.jpg');

Second, is that the width that you've set in the code doesn't match the image's coordinates. In that case, you can either change the code or re-size the image.

And finally, the image might not be loaded on the page and by refreshing it few times it might be shown.

It is not appearing because you didn't give any height to the div see this http://jsfiddle.net/ce1j6k7k/2/ you can remove the height to see the difference

HTML

<div id="image"></div>

CSS

#image{
width:300px;
height:300px;
background-image:url('http://placekitten.com/300/301');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM