How to stretch an image to full width with its height fixed

Viewed 52

I am trying to figure out how to implement the carousel like in this website. I tried using the exact same image from the given website and did something like

div{
    height: 780px;
}

img{
    height: 100%;
    width: 100%;
}
<div>
    <img src = 'xxx'></img>
</div>

Of course, this will not work as expected since it will change the aspect ratio of the image thus messing with its quality. I think what they did was somehow only make the image sized as something like 700px * 780px, then extend it horizontally using just the background color.

2 Answers

You can use object-fit: cover to maintain the aspect ratio of images inside their containers.

The width of the box can change to anything while the image expands and contracts to cover it's parent element.

Added the animation for visuals only. Of course in your project you could set any width that makes sense.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html, body, img {
  width: 100%;
  height: 100%;
}
body {
  display: flex;
  justify-content: center;
  align-items: center;
}
div {
  border-style: solid;
  width: 10rem;
  height: 10rem;
  animation-name: expand;
  animation-duration: 1s;
  animation-timing-function: ease-in-out;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}
img {
  object-fit: cover;
  object-position: center;
}
@keyframes expand {
  100% {
    width: 30rem;
  }
}
<div>
  <img src='https://i.imgur.com/0Zn5PLC.png'>
</div>

You are absolutely right.

On that site, they are setting the height of the image to 480px and setting the width to auto

The img is contained in a div. That div has the background-color set dynamically by JavaScript. They are using color values associated with each slide's background color.

.img-container {
  background: #f5a738;
  width: 100%;
  height: 200px;
  text-align: center;
}

.img-container img {
  height: 200px;
}
<div class='img-container'>
  <img src='https://i.stack.imgur.com/h2STW.png' />
</div>

Here's an example with a different background color so you can see where the image ends:

.img-container {
  background: #a33;
  width: 100%;
  height: 200px;
  text-align: center;
}

.img-container img {
  height: 200px;
}
<div class='img-container'>
  <img src='https://i.stack.imgur.com/h2STW.png' />
</div>

Related