croraf
croraf

Reputation: 4728

Different rendering of HTML (images) depending on DOCTYPE

Why does the rendering with DOCTYPE have the unwanted effect of having the additional spacing after the first image. The unwanted space is in the position where the 0px height image would be?

Without DOCTYPE: https://codesandbox.io/s/image-taking-space-in-block-layout-forked-76oyl?file=/index.html

<html>
  <body>
    <div style="background-color: red;">
      <img
        alt="asd"
        src="https://www.wallpaperuse.com/wallp/0-1226_m.jpg"
        width="500"
        height="500"
        style="height: 200px;"
      />
      <img
        alt="asd"
        src="https://www.wallpaperuse.com/wallp/0-1226_m.jpg"
        width="500"
        height="500"
        style="height: 0px;"
      />
    </div>
  </body>
</html>

With DOCTYPE: https://codesandbox.io/s/image-taking-space-in-block-layout-forked-rlsct?file=/index.html

<!DOCTYPE html>
<html>
  <body>
    <div style="background-color: red;">
      <img
        alt="asd"
        src="https://www.wallpaperuse.com/wallp/0-1226_m.jpg"
        style="width: 500px; height: 200px;"
      />
      <img
        alt="asd"
        src="https://www.wallpaperuse.com/wallp/0-1226_m.jpg"
        style="width: 500px; height: 0px;"
      />
    </div>
  </body>
</html>

Upvotes: 3

Views: 113

Answers (1)

dpwr
dpwr

Reputation: 2812

When DOCTYPE is not specified, the browser renders it in "Quirks mode", which is a backwards compatible mode for older pages designed for ancient browsers. It thus renders things as was intended (as best as the browser can guess) in times of yore.

So, basically, when you get that extra offset, that is the correct HTML rendering according to W3C specs.

I suggest that images that should not be displayed are set to hidden or a similar solution, rather than setting their height to 0px.


Original Suggestion before edited question (when React was involved):

I think you'd be better off with code that only renders the image you want to see (I infer this from your original example). Something like this:

const App = img_src => (
  <div>
    <img
      alt="asd"
      src={img_src}
      width="500"
      height="500"
    />
  </div>
);

Upvotes: 4

Related Questions