html - 如何自动使 div 的高度适合其背景图像?

标签 html css responsive-design

我正在尝试创建本网站第一部分的效果: 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>元素,同时指定 widthheight以前在您的容器上。完全省略 heightwidth来自父级,父级将自动扩展到图像的大小。

这可以从以下方面看出:

.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/

相关文章:

html - 未应用外部文件中的 SVG 过滤器

HTML+CSS 阴影、垂直菜单、文本位置

javascript - Bootstrap Navbar-Collapse 不起作用

css - 如何将 srcset 和 sizes 用于响应式图像

jquery - 有数百个选项的选择可能的 UI 替换?

javascript - 无法更改滚动条值

html - Div 的按钮元素内部未显示在 Firefox 中

javascript - 来自 Chart.js 的堆叠组栏 : Can I give each stack group a unique color?

javascript - 自动居中列表项/图像 100% 页面高度

javascript - 具有可变行/列大小的 Jquery 移动响应网格