使div与背景图像一样高

Sve*_*ven 0 html css bootstrap-4

我知道有类似的问题,但没有一个对我有用。

我有一个带有背景图像的 div 类:

    #index-box{
        border-radius: 20px;
        background: url('/static/images/bg.png') no-repeat;
        background-size: cover;
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法让#index-boxdiv 等级如此之高,以至于整个背景图像都适合?

Yos*_*sky 5

如果您知道图像的长宽比,则可以将所有图像放入具有百分比填充和相对位置的容器中。然后是另一个框的全宽和高以及内容的绝对位置。对于下图,图像的原始尺寸为1280X720,因此高度/宽度的比率为 0.5625

#background {
  position: relative;
  padding-bottom: 56.25%;
  background-image: url('https://i.ytimg.com/vi/MPV2METPeJU/maxresdefault.jpg');
  background-size: cover;
}
#content{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="background">
<div id="content">some content<div>
</div>
Run Code Online (Sandbox Code Playgroud)

此外,通过类似的方式,您始终可以使用图像作为img元素。所以你甚至不需要知道纵横比。像那样:

#container {
  position: relative;
}
#bg {
  width: 100%;
  display: block;
}
#content{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
Run Code Online (Sandbox Code Playgroud)
<div id="container">
<img id="bg" src="https://i.ytimg.com/vi/MPV2METPeJU/maxresdefault.jpg"/>
<div id="content">some content</div>
</div>
Run Code Online (Sandbox Code Playgroud)