HTML Anchors with 'name' or 'id'?

When one wants to refer to some part of a webpage with the " http://example.com/#foo " method, should one use

<h1><a name="foo"/>Foo Title</h1>

or

<h1 id="foo">Foo Title</h1>

They both work, but are they equal, or do they have semantic differences?


According to the HTML 5 specification, 5.9.8 Navigating to a fragment identifier:

For HTML documents (and the text/html MIME type), the following processing model must be followed to determine what the indicated part of the document is.

  • Parse the URL, and let fragid be the <fragment> component of the URL.
  • If fragid is the empty string, then the indicated part of the document is the top of the document.
  • If there is an element in the DOM that has an ID exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  • If there is an a element in the DOM that has a name attribute whose value is exactly equal to fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.
  • Otherwise, there is no indicated part of the document.
  • So, it will look for id="foo" , and then will follow to name="foo"

    Edit: As pointed out by @hsivonen, in HTML5 the a element has no name attribute. However, the above rules still apply to other named elements.


    You shouldn't use <h1><a name="foo"/>Foo Title</h1> in any flavor of HTML served as text/html , because the XML empty element syntax isn't supported in text/html . However, <h1><a name="foo">Foo Title</a></h1> is OK in HTML4. It is not valid in HTML5 as currently drafted.

    <h1 id="foo">Foo Title</h1> is OK in both HTML4 and HTML5. This won't work in Netscape 4, but you'll probably use a dozen other features that don't work in Netscape 4.


    I have to say if you are going to be linking to that area in the page... such as page.html#foo and Foo Title isn't a link you should be using:

    <h1 id="foo">Foo Title</h1>
    

    If you instead put an <a> reference around it you're headline will be influenced by an <a> specific CSS within your site. It's just extra markup, and you shouldn't need it. It'd highly recommend to going with placing an id on the headline, not only is it better formed, but it will allow you to either address that object in Javascript or CSS.

    链接地址: http://www.djcxy.com/p/2556.html

    上一篇: 为HTML 5 +所有浏览器选择DOCTYPE

    下一篇: 带'name'或'id'的HTML锚点?