将 div 放在锚内是否正确? [英] Is putting a div inside an anchor ever correct?
问题描述
我听说将块元素放在内联元素中是一种 HTML 罪:
<div>我们这里有一个问题.你看,一个锚元素是一个内联元素,div 元素是块级元素.
</a>
但是,如果您在样式表中将外部锚点设置为 display:block
呢?还是错了?HTML 4.01 规范关于块级和内联元素 似乎是这么认为的:
样式表提供了指定任意渲染元素,包括是否一个元素呈现为块或内联.在某些情况下,例如内联样式对于列表元素,这可能是适当的,但一般来说,不鼓励作者超越常规对 HTML 元素的解释这样.
有人对这个问题有什么进一步的建议吗?
取决于您迎合的 HTML 版本:
HTML 5 声明
元素可以包裹整个段落、列表、表格等,甚至整个部分,所以只要其中没有互动内容(例如按钮或其他链接)".
- 是块元素,所以它可能不会出现在
中.
当然,您可以自由地设置内联元素的样式,使其看起来是一个块,或者确实设置一个块的样式以使其内联呈现.HTML 中术语
inline
和block
的使用指的是元素与文档语义结构的关系,而 CSS 中的相同术语更多地与文档的语义结构相关.元素的视觉样式.如果您让内联元素以块状方式显示,那很好.但是,当 CSS 不存在时,您应该确保文档的结构仍然有意义,例如当通过辅助技术(如屏幕阅读器)访问时 - 或者确实由强大的 Googlebot 检查时.
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
andblock
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屋!
查看全文