Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different rendering of HTML (images) depending on DOCTYPE

Tags:

html

css

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>

like image 819
croraf Avatar asked Dec 04 '25 17:12

croraf


1 Answers

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>
);
like image 177
dpwr Avatar answered Dec 06 '25 21:12

dpwr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!