Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

html - Why Can't You Put <body> content in the <head> element?

My friend has tried to code a website like this

<html>
  <head>
    <style>
      h1 {
        color: red;
      }
    </style>
    <div>
      <h1>
        My Website
      </h1>
    </div>
  </head>
  <body>
    <nav>
      <a>example link</a>
    </nav>
</body>

he hasn't used <!DOCTYPE html> and he has also put his page header in the <head> element. when I try to tell him that you need a <!DOCTYPE html> and you cant put content in the <head> element he says well it worked and you still haven't told me what's wrong with doing that. I don't know to explain it to him so can someone please say why you can't do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The structure your friend proposes violates the global structure of an HTML document; the <body> tag must contain the document's actual content, whereas the <head> tag must only contain information describing the document.

The incorrect markup will in fact render correctly on the page, because most browsers are actually intelligent enough to know that the markup is incorrect, and correct it themselves. If you inspect the DOM, you'll find that it has automatically been updated to correctly shift the <div> element (and its content) to within the <body> element (just before <nav>):

Fixed


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...