Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 359
MeV Avatar asked Dec 11 '15 12:12

MeV


2 Answers

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

like image 50
yunzen Avatar answered Sep 30 '22 16:09

yunzen


If the image(s) you want to display in the background property always has the same aspect ratio, you can use one of the techniques explained here to make the div keep the same aspect ratio as the image according to the width.

With your example it would look like this :

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

Note that I don't know what you are trying to achieve exaclty. Using this method to display an image probably isn't semanticaly correct depending on the context.

like image 27
web-tiki Avatar answered Sep 30 '22 15:09

web-tiki