LoginSignup
23
13

More than 3 years have passed since last update.

通称visually-hiddenについて

Last updated at Posted at 2020-04-13

これはなに

アクセシビリティ対応意識でのマークアップとして非常に利便性のある通称visually-hiddenというCSSスニペットがあります。
Qiitaで検索した際に特段ヒットしなかったので備忘録件、皆さんもぜひ使ってみてください!

どういう恩恵があるか

視覚的には要素を見えないように非表示にしたいけど、スクリーンリーダーでは読ませたい場合。
visually-hiddenを書いてclassをつけるだけで視覚的にだけ表示させなくできます。
メリットはこれだけではないと思いますが。(SEOとか)

どういう時に使えるか

デザイン上はない、ブラウザの表示上いらない要素だけどHTMLの構造をきちんと書く場合です。
例えば見た目明らかに見出しコンテンツ(h2,h3)に見えるけどやむを得なくh2,h3でマークアップできない状況や、
インプットフォームでlabel要素が、デザイン上テキストが無い時にスクリーンリーダーでは読み上げさせることができます。

  • display:noneは読み上げはされません。
  • visibility: hiddenは要素のスペースができてしまう。
  • visually-hiddenは読み上げができてスペースはできません。

汎用性があるのでいろいろな場面で活用できると思います。

コード

/**
 * Makes elements visually invisible but still accessible to screen-readers.
 *
 * This Css has been carefully tested to ensure screen-readers can read and
 * activate (in case of links and buttons) the elements with this class. Please
 * use caution when changing anything, even seemingly safe ones. For example
 * changing width from 1 to 0 would prevent TalkBack from activating (clicking)
 * buttons despite TalkBack reading them just fine. This is because
 * element needs to have a defined size and be on viewport otherwise TalkBack
 * does not allow activation of buttons.
 */
.visually-hidden {
  position: fixed !important;
  /* keep it on viewport */
  top: 0px !important;
  left: 0px !important;
  /* give it non-zero size, VoiceOver on Safari requires at least 2 pixels
     before allowing buttons to be activated. */
  width: 4px !important;
  height: 4px !important;
  /* visually hide it with overflow and opacity */
  opacity: 0 !important;
  overflow: hidden !important;
  /* remove any margin or padding */
  border: none !important;
  margin: 0 !important;
  padding: 0 !important;
  /* ensure no other style sets display to none */
  display: block !important;
  visibility: visible !important;
}

*コード内容更新しコメントも残しておきます。class名はそのまま。
越智さんありがとうございます!

おわりに

とても便利なスニペットですが、もちろんただ使えば良いわけではないのできちんとスクリーンリーダー対応するならスクリーンリーダーでのコンテキストをきちんと確認してから使用しましょう!!

参考

23
13
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
13