Home > Enterprise >  how to set div height as background image?
how to set div height as background image?

Time:02-01

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>

CodePudding user response:

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>

  • Related