What should come first in HTML, an anchor or a header? [duplicate]

主宰稳场 提交于 2019-11-27 23:12:40

问题


This question already has an answer here:

  • Which is more correct: <h1><a>…</a></h1> OR <a><h1>…</h1></a> 7 answers

I'm wondering which of the following two orders is semantically correct in HTML:

1. <h1><a>Header</a></h1>
2. <a><h1>Header</h1></a>

回答1:


<h1><a>Header</a></h1>

<h1> is a block-level element and <a> is not, it is syntactically invalid HTML to have block level elements inside inline elements (at least until HTML5) which is how the other way would be.




回答2:


This answer on a duplicate question is better than mine: https://stackoverflow.com/a/7023551/20578

But, for posterity:


Semantically, there’s no difference. Remember, “semantic” just means “related to meaning”, and meaning is just something agreed between humans (because computers don’t natively do meaning, that’s a human brain thing). No-one’s got time to agree that one of these virtually identical options means something different to the other :)

Surprisingly, they’re actually both valid as well, as of the current HTML spec, because <a>’s content model is defined as “transparent”, i.e. the same as its parent.

See:

  • http://www.pauldwaite.co.uk/test-pages/5341451

And:

  • http://html5.validator.nu/?doc=http%3A%2F%2Fwww.pauldwaite.co.uk%2Ftest-pages%2F5341451%2F&showsource=yes

(That assumes that <a>’s parent can have an <h1> as its child)

However, it’s not valid under previous versions of HTML:

  • http://validator.w3.org/check?uri=http%3A%2F%2Fwww.pauldwaite.co.uk%2Ftest-pages%2F5341451&charset=%28detect+automatically%29&doctype=HTML+4.01+Transitional&group=0



回答3:


From a semantic perspective: both (or neither).

(From a structural perspective, OTOH, before HTML 5 an anchor cannot contain a heading, and since browsers aren't all HTML 5 capable yet you should avoid the new form of the construct where possible)

If you are creating a link target, then <h1 id="target_name"> is preferred to <h1><a name="target_name"> anyway.

If you are creating a hyperlink, then having the most important heading on the page link somewhere else is somewhat dubious from a semantic point of view.




回答4:


I'd say <h1><a>, because <h*> are block elements and <a> is inline element, so it seems more natural to keep the inline element inside a div block, not the other way round.




回答5:


The header should be first in my opinion but I doubt that search engines would really mind what way round they are, inside the H1 just seems cleaner to me...




回答6:


Since h1 does not directly correspond to a viewable object they both are correct.



来源:https://stackoverflow.com/questions/5341451/what-should-come-first-in-html-an-anchor-or-a-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!