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

前端 未结 3 656
余生分开走
余生分开走 2020-11-28 04:30

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

3条回答
  •  自闭症患者
    2020-11-28 05:01

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

    MDN confirms that:

    Changing the value of the CSS display property on an element with the hidden attribute overrides the behavior.

    And we can show this straightforwardly:

    .hidden {
      display:none;
    }
    
    .not-hidden {
      display: block
    }
    
    
    
    

    This reveals that there is zero presentational difference between:

    • a)
    • b)

    Adding Accessibility:

    However... there's more to consider than visual presentation. We should also all be catering to screen-readers to maximise accessibility (right?), so the second option immediately above should, more properly, look like this:

    • b)

    Why is using a class="hidden" and aria-hidden="true" better than using hidden?

    Because we know that CSS can be over-ridden using either the cascade or specificity and we know that aria-hidden speaks to accessibility user-agents like screen-readers.

    By contrast, the HTML5 hidden attribute is much sketchier. It doesn't say explicitly what it does or doesn't do - and, worse, it appears to suggest it does things it actually doesn't.

    See: https://meowni.ca/hidden.is.a.lie.html


    Final Note:

    Whatever combination of HTML, CSS and ARIA you go with, note that:

    We already have 6 methods for hiding content with different purposes/intentions.

    1. display: none;
    2. visibility: hidden; (don't show, but still hold the space)
    3. opacity: 0;
    4. width: 0; height: 0;
    5. aria-hidden="true"
    6. and in the case of form data, input type="hidden"

    Source: https://davidwalsh.name/html5-hidden#comment-501242

提交回复
热议问题