Img doesn't respect width in html (with flexbox)

Viewed 133

I have some html that should create an image up top, and an image gallery underneath.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>your page title goes here</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="index.css" />
</head>
<body>
  <div class="container">
    <h1>My Photo Gallery</h1>
    <div class="gallery">
      <figure>
        <img src="img/dog1.jpeg" alt="first dog">
        <figcaption>Example Photo</figcaption>
      </figure>
      <div class="img-bar">
        <img src="img/dog2.jpeg" alt="second dog"/>
        <img src="img/dog3.jpeg" alt="third dog"/>
        <img src="img/dog4.jpeg" alt="fourth dog"/>
        <img src="img/dog5.jpeg" alt="fifth dog"/>
      </div>
    </div>
  </div>
</body>
</html>

In order to style the image gallery, I've added the following styles:

.img-bar{
  display: flex;
}

img {
  width: 100%;
}

.img-bar img {
  object-fit: cover;
  width: 300px;
  height: 300px;
}

All of the image files have dimensions > 300px by 300px, so I would expect them to follow the CSS rules. However, as you can see from the photo below, the second image doesn't follow the rules (it's taller than it is wide). As an fyi, the actual dimensions of that image file are 934px x 1401px.

Any help would be appreciated! Thanks.

enter image description here

1 Answers

You want to set the dimensions of your container, then have the image inside expand to fill it. I'd reshuffle it like this:

img {
  width: 100%;
  height: 100%;
  object-fit:cover;
}

.img-bar {
  display:flex;
  width: 300px;
  height: 300px;
}

This will of course apply to all images, so you might want to either add a class for the images inside img-bar or set the dimensions for your figure element containing the main image.

Related