将 div 放在锚内是否正确? [英] Is putting a div inside an anchor ever correct?

查看:32
本文介绍了将 div 放在锚内是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说将块元素放在内联元素中是一种 HTML 罪:

<div>我们这里有一个问题.你看,一个锚元素是一个内联元素,div 元素是块级元素.

</a>

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

<块引用>

样式表提供了指定任意渲染元素,包括是否一个元素呈现为块或内联.在某些情况下,例如内联样式对于列表元素,这可能是适当的,但一般来说,不鼓励作者超越常规对 HTML 元素的解释这样.

有人对这个问题有什么进一步的建议吗?

解决方案

取决于您迎合的 HTML 版本:

I've heard that putting a block element inside a inline element is a HTML sin:

<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>

But what about if you style the outer anchor as display:block in the stylesheet? Is it still wrong? The HTML 4.01 spec on block-level and inline elements seems to think so:

Style sheets provide the means to specify the rendering of arbitrary elements, including whether an element is rendered as block or inline. In some cases, such as an inline style for list elements, this may be appropriate, but generally speaking, authors are discouraged from overriding the conventional interpretation of HTML elements in this way.

Does anyone have any further tips about this issue?

解决方案

Depending on the version of HTML you're catering to:

  • 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.

这篇关于将 div 放在锚内是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆