Skip to content

Instantly share code, notes, and snippets.

@luismartinezs
Last active September 4, 2022 19:04
Show Gist options
  • Save luismartinezs/e344f5ba94484ac66695e7bc8dce2198 to your computer and use it in GitHub Desktop.
Save luismartinezs/e344f5ba94484ac66695e7bc8dce2198 to your computer and use it in GitHub Desktop.
Label form controls #a11y #html
<!-- https://www.w3.org/WAI/tutorials/forms/labels/ -->
<!-- simple labels -->
<label for="firstname">First name:</label>
<input type="text" name="firstname" id="firstname" />
<!-- Cases where label text is hidden -->
<!-- Hide label text with CSS -->
<style>
/* Puts label in 1x1 pixel area. Use only with labels */
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
</style>
<label for="search" class="visuallyhidden">Search: </label>
<input type="text" name="search" id="search" />
<button type="submit">Search</button>
<!-- Use aria-label and omit label element -->
<!-- Supported by screen readers but not conveyed visually -->
<input type="text" name="search" aria-label="Search" />
<button type="submit">Search</button>
<!-- Use aria-labelledby -->
<input type="text" name="search" aria-labelledby="searchbutton" />
<button id="searchbutton" type="submit">Search</button>
<!-- Use title attribute -->
<!-- Shown visually on hover -->
<!-- Not recommended, because some screen readers do not interpret title as replacement for label -->
<input title="Search" type="text" name="search" />
<button type="submit">Search</button>
<!-- Implicit labels: wrap input in label -->
<!-- Use when you don't know the id of the form field, or it doesn't have one -->
<!-- Prefer explicit labels -->
<label>
First name:
<input type="text" name="firstname">
</label>
<!-- Labeling buttons. For buttons it's the text content, for inputs as buttons, it's the value attribute -->
<button type="submit">Submit</button>
<input type="submit" value="Submit">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment