我听说在内联元素中放入块元素是一种HTML错误:

<a href="http://example.com">
    <div>
        What we have here is a problem. 
        You see, an anchor element is an inline element,
        and the div element is a block level element.
    </div>
</a>

但是如果在样式表中将外部锚设置为display:block呢?还是错的吗?关于块级和内联元素的HTML 4.01规范似乎是这样认为的:

样式表提供了实现的方法 指定任意的呈现 元素,包括是否为元素 呈现为块或内联。在 有些情况,比如内联样式 对于列表元素,这可能是 恰当,但总的来说, 不鼓励作者 超越常规 HTML元素的解释 这种方式。

有没有人对这个问题有进一步的建议?


当前回答

任何方法都有用……直到你把它们嵌在一起。

你可以把表格、div、鸟和蜜蜂塞进去,浏览器会耐心地配合你。但是一旦你把另一个<a>标签放在里面,它就会把它们分开,把里面的标签放在外面的标签关闭之后。这值得一试,即使是在F12控制台,当你的浏览器不喜欢某些东西时,你会惊讶地发现它是多么严格。

所以没有这样的事情:

<a href="#1">
    <a href="#2"> Now what </a>
</a>

相反,它将变成:

<a href="#1"></a>
<a href="#2"> Now what </a>

同样的事情发生在<p>和其他一些;事实上,有一篇关于这个的Stacko文章-我可以嵌套这些标签吗?-唯一的答案有关键,在“HTML规范指示”部分寻找项目符号列表。最挑剔的显然是a和p,如h1..h6。(现在让我们诚实地说:你是否曾经专门使用p标签,因为它给了你别人没有的东西?……这么想的。我就把它扔了。)

TL, DR,你不能把a放在a里面。

其他回答

不,它不会验证,但它通常会在现代浏览器中工作。也就是说,在你的锚中使用一个span,并在它上设置display: block,这肯定会在任何地方工作,它会验证!

你可以通过添加"::before"伪元素来实现

纯CSS技巧;)

a:before{ position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1; pointer-events: auto; content: ""; background-color: rgba(0,0,0,0); } <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/> <div class="card" style="width: 18rem;"> <img src="https://via.placeholder.com/250" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Card with stretched link</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary stretched-link">Go somewhere</a> </div> </div>

如果你将它更改为块风格元素,那么不,它不再是“错误的”,但它可能不会被验证。但你现在所做的并没有多大意义。你应该保持锚标记作为一个块级元素,没有内部div,或者把div放在外面。

根据你要迎合的HTML版本:

HTML 5 states that the <a> element "may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links)". HTML 4.01 specifies that <a> elements may only contain inline elements. A <div> is a block element, so it may not appear inside an <a>. Of course you are at liberty to style an inline element such that it appears to be a block, or indeed style a block so that it is rendered inline. The use of the terms inline and block in HTML refers to the relationship of the elements to the semantic structure of the document, whereas the same terms in CSS are related more to the visual styling of the elements. If you make inline elements display in a blocky manner, that's fine. However you should ensure that the structure of the document still makes sense when CSS is not present, for example when accessed via an assistive technology such as a screen reader - or indeed when examined by the mighty Googlebot.

HTML5规范…现在可以将块级元素放入内联元素中。所以现在在一个'a'元素里面放一个'div'或者'h1'是非常合适的。