What is the difference between visibility:hidden and display:none?

前端 未结 18 1593
余生分开走
余生分开走 2020-11-21 04:50

The CSS rules visibility:hidden and display:none both result in the element not being visible. Are these synonyms?

18条回答
  •  名媛妹妹
    2020-11-21 05:18

    There are a lot of detailed answers here, but I thought I should add this to address accessibility since there are implications.

    display: none; and visibility: hidden; may not be read by all screen reader software. Keep in mind what visually-impaired users will experience.

    The question also asks about synonyms. text-indent: -9999px; is one other that is roughly equivalent. The important difference with text-indent is that it will often be read by screen readers. It can be a bit of a bad experience as users can still tab to the link.

    For accessibility, what I see used today is a combination of styles to hide an element while being visible to screen readers.

    {
      clip: rect(1px, 1px, 1px, 1px);
      clip-path: inset(50%);
      height: 1px;
      width: 1px;
      margin: -1px;
      overflow: hidden;
      padding: 0;
      position: absolute;
    }
    

    A great practice is to create a "Skip to content" link to the anchor of the main body of content. Visually-impaired users probably don't want to listen to your full navigation tree on every single page. Make the link visually hidden. Users can just hit tab to access the link.

    For more on accessibility and hidden content, see:

    • https://webaim.org/techniques/css/invisiblecontent/
    • https://webaim.org/techniques/skipnav/

提交回复
热议问题