1

I have used this approach https://stackoverflow.com/a/22211990

Only problem is that as soon as I enter text/content in div like this: <div>abc</div>

That text appear under the image.

Code: https://codepen.io/labeeb/pen/JMxzQY

* {
  padding: 0px;
  margin: 0px;
}

.image {
  background: url('https://i.pinimg.com/originals/4f/d6/ef/4fd6ef1f078ca5e229ce5925c10f194a.jpg') no-repeat;
  background-size: 100%;
  background-size: contain;
  height: 0;
  padding-top: 100.44%; /* (bg image width/ bg image height) * 100*/
}
<div class="image">aaa</div>
Stickers
  • 75,527
  • 23
  • 147
  • 186

2 Answers2

0

You can give the image element position:relative and wrap the text in an element with position:absolute and top:0

*{
  padding:0px;
  margin:0px;
}

.relative {
  position:relative;
}

.text {
  position: absolute;
  color: red;
  top:0;
}

.image{
  background:url('https://i.pinimg.com/originals/4f/d6/ef/4fd6ef1f078ca5e229ce5925c10f194a.jpg') no-repeat;
  background-size:100%;
  
  height:0;
  padding-top:100.44%;  /* (bg image width/ bg image height) * 100*/
  
}
<div class="image relative">
    <div class="text">aaa</div>
</div>
cfreear
  • 1,855
  • 2
  • 19
  • 25
0

For me : you choice is a bad strategy, because de the padding-top will always impact your content. It is not the background job.

My solution : combine height 100vh and background-size cover.

*{
  padding:0px;
  margin:0px;
}

.image{
  color: white;
  height: 100vh;
  background:url('https://i.pinimg.com/originals/4f/d6/ef/4fd6ef1f078ca5e229ce5925c10f194a.jpg') no-repeat;
  background-size:cover;
  }
<div class="image">aaa</div>
Sylvain
  • 238
  • 2
  • 15
  • The goal is to adjust the height of a div to the aspect ratio of the image set as the background not to cover the viewport. – cfreear Jan 21 '18 at 18:50