有多种方法可以让背景图片自动适应div容器大小。

  1. 使用CSS的'background-size'属性:
<div class='container'></div>

<style>
.container {
  background-image: url('your-image.jpg');
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  width: 100%;
  height: 100%;
}
</style>

这样设置后,背景图片将按比例缩放,以覆盖整个div容器。

  1. 使用CSS的'background-size'属性和'background-image'的属性值设置:
<div class='container'></div>

<style>
.container {
  background-image: url('your-image.jpg');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  width: 100%;
  height: 100%;
}
</style>

这样设置后,背景图片将按比例缩放,以适应整个div容器,并且完全显示图片。

  1. 使用CSS的'background-size'属性和'background-image'的属性值设置,并通过JS动态调整div容器的大小:
<div id='container'></div>

<style>
#container {
  background-image: url('your-image.jpg');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}
</style>

<script>
window.onload = function() {
  var container = document.getElementById('container');
  var image = new Image();
  image.src = 'your-image.jpg';
  image.onload = function() {
    var width = image.width;
    var height = image.height;
    container.style.width = width + 'px';
    container.style.height = height + 'px';
  }
}
</script>

这样设置后,JS会在图片加载完成后,获取图片的宽度和高度,并将div容器的大小设置为图片的宽度和高度。


原文地址: https://www.cveoy.top/t/topic/pftA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录