0

I have an image which I want to be displayed inside my div. I want it to occupy my hero section.

Problem is, when I use contain, it doesn't fill the whole div and empty space is left after image. When I use cover, it doesn't show complete image rather it clips/crop majority of the image. Am I doing anything wrong?

body {
  text-align: center;
  margin: 0;
}

.hero {
  background-image: url("https://img.theculturetrip.com/450x/smart/wp-content/uploads/2018/07/shutterstock_697606678.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  width: 100%;
  height: 300px;
}
<body>
  <div class="hero"></div>
</body>
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    You're not doing it wrong, but _you can't warp time and space_. Your image has a shape, and if the container doesn't have exactly the same shape, _something has to give_. Pick your poison. – isherwood Jul 12 '23 at 16:17
  • This may help: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size – isherwood Jul 12 '23 at 16:19
  • And this: https://cssreference.io/property/background-size/ – isherwood Jul 12 '23 at 16:21
  • @isherwood got it! so how do we find a workaround to this problem? – Coca Coffee Jul 12 '23 at 16:22
  • There's no _problem_. There's a _choice_. If you want the image container to match the image's shape, see https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css – isherwood Jul 12 '23 at 16:24

1 Answers1

0

In this situation I'd use the image as an element then I position it absolutely to its parents:

p.s: Probably it's not the best practice but it works as you want.

body {
  text-align: center;
  margin: 0;
}

.hero {
  background: red;
  width: 100%;
  min-height: 400px;
  position:relative;
  z-index:1;
}
img{
  position:absolute;
  top:0;
  left:0;
  width:100%;
  max-width:1000px;
  min-width:300px;
  z-index:-1;
}
<body>
  <div class="hero">
    <img src='https://img.theculturetrip.com/450x/smart/wp-content/uploads/2018/07/shutterstock_697606678.jpg' />
    <p>some text</p>
    <p>some text</p>
    <p>some text</p>
  </div>
</body>
Maziar Rumiani
  • 641
  • 1
  • 4
  • 11