首页 > 解决方案 > CSS - 根据大小更改背景位置

问题描述

我有一个带有背景图像的 div 部分。div 部分的宽度可变,但高度固定。背景图像始终与 div 部分相同,并且位于底部中心。

footer{
  position: absolute;
  bottom: -20px;
  left: 0;
  right: 0;
  height: 300px;
  width: 100%;
  color: #fff;
  background-color: #7f7f7f;
}

footer::before{
  content: "";
  position: absolute;
  top: 0px;
  height: 100%;
  width: 100%;
  background-image: url("./img.png");
  background-repeat: no-repeat;
  background-size: 100% auto;
  background-position: bottom center;
  opacity: 0.4;
}

如果现在 div 部分变为宽度,则背景图像变为高度并在顶部被剪切。如果图像变为高度,我想将位置更改为顶部中心,因此剪切图像的底部。有没有解决方案来实现这种效果?

标签: cssbackground-imagepositioning

解决方案


您是否尝试将背景大小从 100% 自动更改为“包含”,如下所示:

 background-size: contain;

推荐阅读