Skip to content

Instantly share code, notes, and snippets.

@alastc
Last active December 29, 2015 17:49
Show Gist options
  • Save alastc/7706437 to your computer and use it in GitHub Desktop.
Save alastc/7706437 to your computer and use it in GitHub Desktop.
How to hide content from view, and/or screen readers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<title>Methods to hide content in various ways</title>
<!--
This is an example page, published by @alastc at:
http://alastairc.ac/gists/7706437/hiding-content.html
On Github at:
https://gist.github.com/alastc/7706437
Creative Commons BY-SA 2.0
http://creativecommons.org/licenses/by-sa/2.0/
-->
<style>
.hide {display: none;}
.show-to-at {position: absolute; left: -9999em; outline: 1px red solid ;}
div {outline: 1px grey solid; height: 1.5em;}
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
width: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
position: absolute;
}
</style>
</head>
<body>
<h1>Methods to hide content in various ways</h1>
<p>There are situations where you might want to include hidden elements for screen reader users, or hide things from screen reader users but show them visually. These are the best methods:</p>
<h2>Hide from everyone</h2>
<p>Basically use <code>display: none;</code> in the CSS. Using the HTML5 <code>hidden</code> attribute also works. Still, you have to ask why this content in in the source if it shouldn't be used at all? </p>
<pre><code>.hide {display: none;}
&lt;p class=&quot;hide&quot;&gt;Hidden content&lt;/p&gt;</code></pre>
<p>The following paragraph is hidden:</p>
<div>
<p class="hide">This text should not be read out or seen.</p>
</div>
<h2>Hide from visual rendering, read out by screen readers</h2>
<p>Moving the element off-screen is the best method, e.g. <code>position: absolute; left: -9999em;</code>.</p>
<pre><code>.show-to-at {position: absolute; left: -9999em;}
&lt;p class=&quot;show-to-at&quot;&gt;Hidden from view&lt;/p&gt;</code></pre>
<p>The following paragraph is visually hidden:</p>
<div>
<p class="show-to-at">This text should not be seen, but should be read out.</p>
</div>
<h3>Hiding visually, accounting for various CSS issues</h3>
<p>You can get issues with people incraesing the size of text so things unhide, or mobile performance issues. Taking these into account, the CSS would be:</p>
<pre><code>.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
width: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
position: absolute;
}</code></pre>
<h2>Show in visual rendering, hide from screen readers</h2>
<p>Use <code>aria-hidden</code> to hide things from screen readers whilst showing them in the visual rendering.</p>
<div>
<p aria-hidden="true">This text should be seen but not heard.</p>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment