简体   繁体   中英

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>

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>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM