Bad code
<button display="flex" role="button">
<svg role="img" viewBox="0 0 13 13" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" height="15px" width="15px" fill="#000" name="close">
<title>Close dialog</title>
<path d="…"> </path>
</svg>
</button>
Issues and how to fix them
- Either turn the
<svg>
into a semantic element (role="img"
) or exclude it from the accessibility tree (aria-hidden="true"
). Doing both makes no sense. - The button has no accessible name (a text alternative). The
title
element in thesvg
would serve as the accessible name, butaria-hidden="true"
makes the whole SVG inaccessible to assistive technology. - Even without
aria-hidden="true"
, some screen reader/browser combinations might not recognise the<title>
element. Label the<svg>
usingaria-labelledby
oraria-label
. - The
role=button
attribute and value for the button is redundant. Its implicit default role is “button”. - There's no
display
attribute. If you need custom attributes, use thedata-
prefix. - The
name
attribute is not allowed on<svg>
- The value of the
width
andheight
attributes should be a valid non-negative integer. - Add a
type="button"
attribute and value to prevent the button from submitting a form, if there is one.
Good code
<button type="button" data-display="flex">
<svg role="img" viewBox="0 0 13 13" xmlns="http://www.w3.org/2000/svg" height="15" width="15" fill="#000" aria-labelledby="title">
<title id="title">Close</title>
<path d="…"> </path>
</svg>
</button>
Demo of Voice Over on macOS
Voice Over doesn't recognize the title element nested in a svg nested in a button.
Code on CodePen.