htmlcssoverflowbackground-image

Force div to have the size of background image


When using a background image on a Div I am not able to display the full height of the image, neither using height:auto; or height: 100%. Why so? How can I solve the problem?

I have created a JS Fiddle here: https://jsfiddle.net/2d0npz2v/5/

body, html {
  height: 100%;
  margin: 0px;
}
.imageContainer2 {
  background-image: url("http://i.imgur.com/AWi7r5m.jpg");
  background-position: center top;
  background-size: 100% auto;
  height: 100%;
}
<div class="imageContainer2"></div>

UPDATE Just for clarity, the image needs to be 100% width, and auto height (not cut at the bottom). This example works but it's using the "content" property instead of the "background-image": https://jsfiddle.net/j47a6x7s/. I am looking for the same behaviour but without using content.


Solution

  • Well, the reason why this is?

    In your working example you use content. A content has it's own height and uses up space, which the other elements on the page have to respect.

    With the background-image solution, you use a background, which does not use space. The .imageContainer2 element can not know about the height of the background-image AND adapt itself to it.

    This very problem was addressed here: How to get div height to auto-adjust to background size?
    Just check, if the workaround is suitable for you