我正在尝试创建本网站第一部分的效果: https://www.bandainamcoent.com/games/dragon-ball-fighterz#
div 的高度在调整窗口大小时发生变化,以便背景图像保持其宽高比并且位于 div 底部的链接仍在 View 中。
我当前的方法仅在调整大小时调整背景图像的宽度。我在 div 上设置了一个高度,这样高度就不会塌陷在内容上。但是,我想让背景图像决定高度。
.landingPage {
position: relative; //<--This is only here for some absolutely positioned elements in the div
height: 950px;
width: 100%;
background-image: url(../assets/desktopLandingImage.jpg);
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
最佳答案
元素不可能根据其背景图像的大小展开。
要解决这个问题,我建议将背景图片变成子图片 <img>
元素。关于这个<img>
元素,同时指定 width
和 height
以前在您的容器上。完全省略 height
和 width
来自父级,父级将自动扩展到图像的大小。
这可以从以下方面看出:
.landingPage > img {
width: 100%;
height: 950px;
}
<div class="landingPage">
<img src="http://placehold.it/100">
</div>
希望这对您有所帮助!
关于html - 如何自动使 div 的高度适合其背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47876954/