html - 根据 DOCTYPE 呈现不同的 HTML(图像)

标签 html css

为什么使用 DOCTYPE 渲染会产生在第一个图像之后有额外间距的不良效果。不需要的空间位于 0px 高度图像所在的位置?

没有 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>

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>

最佳答案

当未指定 DOCTYPE 时,浏览器将其呈现为“Quirks mode”,这是为旧版浏览器设计的旧版页面的向后兼容模式。因此,它按照过去的预期(浏览器可以猜测的最好程度)呈现事物。

所以,基本上,当您获得额外的偏移量时,这就是根据 W3C 规范的正确 HTML 呈现。

我建议将不应该显示的图像设置为隐藏或类似的解决方案,而不是将它们的高度设置为0px


编辑问题前的原始建议(涉及 React 时):

我认为您最好使用仅呈现您想要查看的图像的代码(我从您的原始示例中推断出这一点)。像这样:

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

关于html - 根据 DOCTYPE 呈现不同的 HTML(图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65189749/

相关文章:

javascript - 只有一个普通的 html 和 js 文件,我如何强制下载 mp3 的链接而不是播放?

javascript - 使用Java在表单Load上加载select html中的查询结果

angularjs - 如何在没有 jquery 的情况下使用 title 属性创建自定义工具提示

javascript - 下降时,导航栏进入页面内容下方

javascript - 缩小 JS 和 CSS 有什么风险吗?

css - 可合并选择器 SCSS-lint

css - 如何在单击时隐藏可折叠的 Bootstrap 导航栏

javascript - 将 <li> 元素绑定(bind)到按 id 停靠的元素

javascript - 如何将幻灯片应用于向上或向下移动的元素

javascript - CSS/JS : Animate a vertical line on scroll