1

I am 100% at a loss as to why I cannot get a background-image to display. I have tried multiple different images to rule that out. I have also changed src to url, changed the background-size from cover to auto 100%. Nothing I do will get the image to display.

Does anyone see why my background image will not display?

#home-img {
 background-image: url("http://cosmotekcollege.com/wp-content/uploads/2015/08/ban4.png");
 background-repeat: no-repeat;
 background-size: cover;
 background-position: center;
 background-position: 50% 50%;
 width: 100%;
 height: auto;
 position: relative;
}
<div id="home-img">
</div>

Here is jsfiddle

Banzay
  • 9,310
  • 2
  • 27
  • 46
Paul
  • 3,348
  • 5
  • 32
  • 76
  • 4
    Give your div some content or define a height. It has no height as-is – j08691 Feb 13 '17 at 19:35
  • The `height: auto` won't suffice? – Paul Feb 13 '17 at 19:36
  • 1
    When in doubt, right click your page and do *Inspect Element*. If you hover over your `
    ` in the code, it'll highlight it on the page, and you'd find out that it has a height of 0px. `height: auto;` will resize the div to fit its content (which is default behavior regardless), however your div *has no content*. Without any content or a set height, it will be 0px tall.
    – Tyler Roper Feb 13 '17 at 19:36
  • I think your example pretty much answers that question. A background image is just that, a background image; it occupies no space, so your div is collapsing to the smallest possible space it can. – j08691 Feb 13 '17 at 19:37
  • 1
    `height: auto` will depend on the children's height. http://stackoverflow.com/questions/15943009/difference-between-css-height-100-vs-height-auto – bobjoe Feb 13 '17 at 19:37
  • I appreciate the help. – Paul Feb 13 '17 at 19:38

3 Answers3

1

Using Chrome Inspect, I changed the #home-img height from "auto" to 537px and then the image appeared. So updating the height is one option to fix this issue.

Another option is covered in this SO Q&A entry.

How to get div height to auto-adjust to background size?

Community
  • 1
  • 1
JohnH
  • 1,920
  • 4
  • 25
  • 32
1

If you use backgound-image and you don't have content inside div, you always should set height. Here is example https://jsfiddle.net/5pphkLmt/5/

<div id="home-img">
        </div>

#home-img {
    background-image: url("http://cosmotekcollege.com/wp-content/uploads/2015/08/ban4.png");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    background-position: 50% 50%;
    width: 100%;
    height: 540px;
    position: relative;
}
0

you should add height to your code or put something in this DIV, just test height: 100px; and enjoy it :)