我听说在内联元素中放入块元素是一种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元素的解释 这种方式。

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


当前回答

如果你要努力制作<a>块,为什么不把<a>放在div中,作为块元素,它会给你同样的效果。

其他回答

如果你要努力制作<a>块,为什么不把<a>放在div中,作为块元素,它会给你同样的效果。

2023年1月更新:最新HTML5版本

Nothing is wrong with placing a div inside a tag. In fact, you can place just about anything inside a tag as long as they are categorized as transparent, except that no descendant may be interactive content (eg: buttons or inputs) or an a element, and no descendant may have a specified tabindex attribute. Please refer to these documentations: https://www.w3.org/TR/2011/WD-html5-20110525/text-level-semantics.html#the-a-element https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#properties. If you inspect Angular Material official website, you can tell that they are indeed using div inside a element.

这是我从他们的网站上截取的一个例子:

<a href="/components/badge">
  <div class="mat-list-item-content">
    <div mat-ripple="" class="mat-ripple mat-list-item-ripple"></div>
    <div class="mat-list-text"></div>
  </div>
</a>

你可以通过添加"::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>

在HTML5中,<div>这样的块级元素可以用<a>标签来包装。虽然<div>被认为是流内容的容器/包装器,而<a>被认为是根据MDN的流内容。从语义上讲,创建作为块级元素的内联元素可能更好。

W3C文档没有使用错误和罪恶这样的概念,但它确实使用了诸如提供方法、可能是适当的和不鼓励的概念。

实际上,在第4节的第二段中,4.01规范列出了如下的单词

本文件中的关键字“必须”、“必须不”、“要求”、“应当”、“不应当”、“应该”、“不应该”、“建议”、“可能”和“可选”按[RFC2119]解释。但是,为了可读性,这些单词在本规范中不以所有大写字母出现。

考虑到这一点,我相信在7.5.3块级和内联元素中有明确的声明,其中说

通常,内联元素只能包含数据和其他内联元素。

条件“一般”似乎引入了足够的模糊性,说明HTML 4.01确实允许内联元素包含块元素。

当然,CSS2有一个显示属性值inline-block,它似乎适合您所描述的目的。我不确定它是否得到了广泛的支持,但似乎有人预见到了这种行为的需要。

DTD在这里似乎不那么宽容,但DTD的文本遵从规范:

HTML 4.01规范包括额外的 不能在内部表示的语法约束 dtd。

在另一个注释中,您建议通过将块包装在锚中使其激活。我不认为HTML禁止这样做,CSS显然允许这样做。因此,要回答标题中关于它是否正确的问题,我的回答是肯定的。按照标准,这有时是正确的。