What is the difference between the hidden attribute (HTML5) and the display:none rule (CSS)?

让人想犯罪 __ 提交于 2020-01-18 19:37:53

问题


HTML5 has a new global attribute, hidden, which can be used to hide content.

<article hidden>
   <h2>Article #1</h2>
   <p>Lorem ipsum ...</p>
</article>

CSS has the display:none rule, which can also be used to hide content.

article { display:none; }

Visually, they are identical. What is the difference semantically? Computationally?

What guidelines should I consider on when to use one or the other?

TIA.

EDIT: Based on @newtron's responses (below), I did more searching. The hidden attribute was hotly contested last year and (apparently) barely made it into the HTML5 spec. Some argued it was redundant and had no purpose. From what I can tell, the final evaluation is this: If I'm targeting only web browsers, there is no difference. (One page even asserted that web browsers used display:none to implement the hidden attribute.) But if I'm considering accessibility (e.g., perhaps I expect my content to be read by screen-readers), then there is a difference. The CSS rule display:none might hide my content from web browsers, but a corresponding aria rule (e.g., aria-hidden="false") might try to read it. Thus, I now agree that @newtron's answer is correct, though perhaps (arguably) not as clear as I might like. Thanks @newtron for your help.


回答1:


The key difference seems to be that hidden elements are always hidden regardless of the presentation:

The hidden attribute must not be used to hide content that could legitimately be shown in another presentation. For example, it is incorrect to use hidden to hide panels in a tabbed dialog, because the tabbed interface is merely a kind of overflow presentation — one could equally well just show all the form controls in one big page with a scrollbar. It is similarly incorrect to use this attribute to hide content just from one presentation — if something is marked hidden, it is hidden from all presentations, including, for instance, screen readers.

http://dev.w3.org/html5/spec/Overview.html#the-hidden-attribute

Since CSS can target different media/presentation types, display: none will be dependent on a given presentation. E.g. some elements might have display: none when viewed in a desktop browser, but not a mobile browser. Or, be hidden visually but still available to a screen-reader.



来源:https://stackoverflow.com/questions/6708247/what-is-the-difference-between-the-hidden-attribute-html5-and-the-displaynone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!