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