如果父div块的背景图设置为'contain',则背景图会根据父div块的大小进行缩放,保持图像的宽高比。如果你想让父div块的宽度与背景图一样大,可以使用一些CSS技巧来实现:

  1. 使用绝对定位:将父div块设置为相对定位,然后在其内部创建一个绝对定位的子元素,将背景图作为子元素的背景,并设置宽度为100%。
<div class='parent'>
  <div class='child'></div>
</div>
.parent {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 50%; /* 假设背景图的宽高比为2:1 */
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('your-background-image.jpg');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}
  1. 使用伪元素:利用伪元素在父div块内创建一个占满整个div的子元素,然后将背景图设置为伪元素的背景。
<div class='parent'></div>
.parent {
  position: relative;
  width: 100%;
  padding-bottom: 50%; /* 假设背景图的宽高比为2:1 */
}

.parent::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('your-background-image.jpg');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
}

这两种方法都可以让父div块的宽度与背景图一样大。选择哪种方法取决于具体情况和个人喜好。

CSS技巧:让父div块宽度与背景图大小一致 (background-size: contain)

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

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