0

I know there are questions similar to this one, but none of them worked for me.

I have a div class with a background image:

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

Is there any way to make the #index-box div class so high, that the whole background image fits in?

Sven
  • 1,014
  • 1
  • 11
  • 27
  • 1
    CSS doesn’t know how high your background image is. If you know the image dimensions / aspect ratio beforehand, and you want the div to keep that same aspect ratio at any width - then go look into the _padding-bottom hack_. – CBroe Jun 08 '20 at 13:07

2 Answers2

5

If you know the aspect ratio of the image you can put all in a container with percentage padding and relative position. then another box full width and height with absolute position for the content. For the below image the original size of the image is 1280X720, so the ratio height/width 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;
}
<div id="background">
<div id="content">some content<div>
</div>

Also, with similar way you always can use the image as an img element. so you even not need to know the aspect-ratio. like that:

#container {
  position: relative;
}
#bg {
  width: 100%;
  display: block;
}
#content{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}
<div id="container">
<img id="bg" src="https://i.ytimg.com/vi/MPV2METPeJU/maxresdefault.jpg"/>
<div id="content">some content</div>
</div>
Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29
  • thank you, thats even much more better than [here](https://stackoverflow.com/questions/600743/how-to-get-div-height-to-auto-adjust-to-background-size). The answers there were bad and didn't work for me – Sven Jun 08 '20 at 13:53
  • To center your text content, you'd need then to play with the absolute position? – m3.b Nov 09 '21 at 03:08
  • @m3.b not nessesery. you can set `display:flex;justify-content:center;align-items:center` to the div – Yosef Tukachinsky Nov 26 '21 at 07:50
0

try to apply this code:

#index-box{
        border-radius: 20px;
        background: url('/static/images/bg.png') no-repeat;
        background-size: cover;
        object-fit:cover;
    }

or

    body{
    margin:0;
    width:100%;
   }
    #index-box{
            height:100%;
            border-radius: 20px;
            background: url('/static/images/bg.png') no-repeat;
            background-size: cover;
            background-position:center;
        }
Siti Asna
  • 23
  • 1
  • 5