Can we use <a> directly in the body, or it should always in any block level tag? See example (XHTML)

天大地大妈咪最大 提交于 2019-12-11 02:49:30

问题


Which is right? This:

<h2>heading 2</h2>
<p><a href="#" target="_blank" title="Opens in a new window">link 1</a></p>
<h2>heading 2 </h2>
<p><a href="#" target="_blank" title="Opens in a new window">link 2</a></p>
<h2>heading 2 </h2>
<p><a href="#" target="_blank" title="Opens in a new window">link 3</a></p>
<h2>heading 2 </h2>
<p><a href="#" target="_blank" title="Opens in a new window">link 4</a></p>

or this:

<h2>heading 2</h2>
<a href="#" target="_blank" title="Opens in a new window">link 1</a>
<h2>heading 2 </h2>
<a href="#" target="_blank" title="Opens in a new window">link 2</a>
<h2>heading 2 </h2>
<a href="#" target="_blank" title="Opens in a new window">link 3</a>
<h2>heading 2 </h2>
<a href="#" target="_blank" title="Opens in a new window">link 4</a>

回答1:


@Jitendra, I agree with your point .. but only if you are using strict.dtd (HTML/XHTML)
According to W3C recommendation(for strict dtd) .. the tag <a> must be used in a block element.

Look at the following example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
   <meta content="text/html; charset=utf-8" http-equiv="content-type"/>
   <title>example</title>
 </head>
 <body>You don't have sufficient privileges to access the page.<a href="www.google.co.in">Click here</a> to go back.
 </body>
</html>

The above code produces error while doing HTML validation .. saying

document type does not allow element "A" here; missing one of "P", "H1", "H2", "H3", "H4", "H5", "H6", "PRE", "DIV", "ADDRESS" start-tag

Making the dtd as loose/transitional you can get rid of the error .. For Strict HTML or Strict XHTML this error is obvious ..

Hope it helped .. :)

regards-Infant Pro




回答2:


Both are right, both will validate




回答3:


Both are fine but having floating inline elements bothers me for some reason




回答4:


While I have never cared about the "non-block in block element" rule when writing HTML codes, the body element is supposed to be a block element. (I've forgotten where I read it tho') i.e. your both HTML code fragments are right.




回答5:


Neither of them are truly 'right' semantically :-)

Put them as a list and try to avoid the target="_blank". There's probably no reason to put a <p> around each <a> (just ensure that the whole lot is in a block level element if you want to validate with strict - good point infant programmer).

If you want the <a> to act as block level element and thus remove the <p> just use

#somewrapper a
{
 display: block;
}


来源:https://stackoverflow.com/questions/1968122/can-we-use-a-directly-in-the-body-or-it-should-always-in-any-block-level-tag

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