How to make a div have the size of an image and display it?

2

When declaring a div and importing an image as background-image , I need to declare the size ( height and width ) of the div.

However, let's say I have an image size of 900x506 (example). And that I just declared div and did not assign any size ( height and width ) to it. Home Is it possible for me to import the image via css background-image: url('minhaimagem.jpg'); and my div automatically display it, even though I have not assigned any size ( height and width ) to it?


(I do not know if it was very clear, another explanation ..)

How can I declare a div , import an image as background and my div "get" the values of my image ( height and width )?

#imagem{
	
	background-image: url('http://www.planwallpaper.com/static/images/techno_wallpaper_2_0_hd_by_gredius-d5o48do.jpg');
}
<div id="imagem">

</div>
    
asked by anonymous 19.02.2016 / 15:07

2 answers

2

Unfortunately you will not be able to do this with just css, you will need javaScript.

var images = document.querySelectorAll(".default-img-size");

[].forEach.call(images, function (imagem, indice) {
  var style = window.getComputedStyle(imagem, null);
  var background = style.getPropertyValue("background-image");
  var inicio = background.indexOf('(') + 1;
  var final = background.lastIndexOf(')');

  var img = document.createElement("img");
  img.src = background.substring(inicio, final);
  img.addEventListener("load", function () {    
    imagem.style.width = img.width + "px";
    imagem.style.height = img.height + "px";
  })
});
#imagem{	
  background-image: url('http://image005.flaticon.com/3/png/512/2/2612.png');
}
<div id="imagem" class="default-img-size">

</div>
    
19.02.2016 / 17:40
0

There is a very easy way to do this. You need to know the image width and height ratio. Set the height of the div to 0 and set the padding-top as a percentage based on the ratio of the image.

#imagem{
    background-image: url('http://www.planwallpaper.com/static/images/techno_wallpaper_2_0_hd_by_gredius-d5o48do.jpg');
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: 0;
    padding-bottom: 56.22%; 
        /* (img-height / img-width) * container-width) */
        /* (506 / 900) * 100 */ 
}

<div id="imagem">

</div>
    
19.02.2016 / 20:15