Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to set div height as background image?

What I’m trying to achieve is that the height of the DIV will change depending on the image size (without repeat)
I’m looking for a solution with broad browser support,I have already tried almost every answer I found on Google, nothing really worked

<!DOCTYPE html>
<html>
<head>
<style> 
#div_1 {
  width: 250px;
  height: 250px;
  background-image: url("https://i.ibb.co/YRwty0q/11.jpg");
}
#div_2 {
  width: 250px;
  height: 250px;
  background-image: url("https://i.ibb.co/khjZcj2/222.jpg");
}

</style>
</head>
<body>

<div id="div_1"></div>
<div id="div_2"></div>
<script>
  

</script>
</body>
</html>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Load the image with Javascript:

$('div').each(function() {
  const url = getComputedStyle($(this)[0])['background-image'].slice(5, -2)
  const img = new Image()
  img.src = url
  img.onload = () => {
    $(this).css({
      width: img.width,
      height: img.height
    })
  }
})
#div_1 {
  background-image: url("https://i.ibb.co/YRwty0q/11.jpg");
}

#div_2 {
  background-image: url("https://i.ibb.co/khjZcj2/222.jpg");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div_1"></div>
<div id="div_2"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading