我听说在内联元素中放入块元素是一种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中,作为块元素,它会给你同样的效果。

其他回答

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

仅供参考。

如果你的目标是让你的div可点击,你可以使用jQuery / Java Script。

像这样定义你的div:

<div class="clickableDiv" style="cursor:pointer">
  This is my div. Try clicking it!
</div>

然后你的jQuery将像这样实现:

 <script type="text/javascript">

    $(document).ready(function () {

        $("div.clickableDiv").click(function () {
            alert("Peekaboo"); 
        });
    });
</script>

这也适用于多个潜水-根据汤姆的评论在这个线程

你可以通过添加"::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的流内容。从语义上讲,创建作为块级元素的内联元素可能更好。

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