0

In the following code is just an img tag wrapped with a div tag. Nothing else! The image should expand to 100% width of the parent. No other rule provided.

.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>

The result is in all browsers a img with a div tag arround. But it looks like the img has an margin-bottom or the div an padding-bottom. So let us add margin: 0; padding: 0; to all elements:

.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>

Still the same result... The only solution to let both elements be the same widht and height (as every nested block element should be) is to add a display: flex; to the wrapping div. WTF?

Can someone explain WHY they specified this really illogical default behavior?

Twak
  • 127
  • 11
Tobi
  • 674
  • 5
  • 20

1 Answers1

2

it's because image tag has by default rendered inline so, change it with 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>
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41