为什么 img 标签周围的 div 总是比 img 大?

Why is a div arround an img tag always larger then the img?

下面的代码只是用 div 标签包裹的 img 标签。没有其他的!图片应扩展到父级的 100% 宽度。没有提供其他规则。

.page {
  max-width: 300px;
}

.wrapper {
  border: 2px dotted green;
}

img {
  width: 100%;
}
<div class="page">

  <div class="wrapper">
    <img src="https://images.unsplash.com/photo-1604869176104-fcd142638bd9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80" alt="random image">
  </div>


</div>

结果在所有浏览器中都是带有 div 标记的 img。但它看起来像 img 有一个边距底部或 div 一个填充底部。 因此,让我们将 margin: 0; padding: 0; 添加到所有元素:

.page {
  max-width: 300px;
}

.wrapper {
  border: 2px dotted green;
}

img {
  width: 100%;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
<div class="page">

  <div class="wrapper">
    <img src="https://images.unsplash.com/photo-1604869176104-fcd142638bd9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80" alt="random image">
  </div>


</div>

还是一样的结果... 让两个元素具有相同宽度和高度(每个嵌套块元素都应该如此)的唯一解决方案是向包装 div 添加一个 display: flex;。什么鬼?

有人可以解释为什么他们指定了这种非常不合逻辑的默认行为吗?

这是因为图像标签默认内联渲染,所以,将其更改为 display:block;

.page {
  max-width: 300px;
}

.wrapper {
  border: 2px dotted green;
}

img {
  width: 100%;
  display:block;
}
<div class="page">
  <div class="wrapper">
    <img src="https://images.unsplash.com/photo-1604869176104-fcd142638bd9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=700&q=80" alt="random image">
  </div>
</div>