Why does the image in my `<img>` tag appear larger than its specified width within a flex container?

Why does the image in my <img> tag appear larger than its specified width within a flex container? Here’s my HTML and CSS code:

HTML:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>

<div class="container">
  <img src="image.jpg" alt="Sample Image" class="image">
</div>

</body>
</html>

CSS (styles.css):

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}

.image {
  width: 100px;
  height: auto;
}

I expected the image to be 100 pixels wide, but it appears larger than that within the flex container. What am I doing wrong in the CSS that’s causing the image to not adhere to the specified width?

1 Like

Did you try adding display: block to the .image class?

1 Like