<!-- This is a demo for https://zenn.dev/taigakiyokawa/articles/20231120-icon-button-accessible-name -->

<h2>1. button要素にaria-labelを付与して、svg要素にaria-hidden="true"を付与する</h2>
<button type="button" aria-label="閉じる">
  <svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M6 6l12 12M6 18L18 6" stroke="#000" stroke-width="2"/>
  </svg>
</button>

<h2>2. button要素内にVisually Hiddenなクラスを持たせたspan要素でテキストを入れて、svg要素にaria-hidden="true"を付与する</h2>
<button type="button">
  <span class="visually-hidden">閉じる</span>
  <svg aria-hidden="true" width="24" height="24" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M6 6l12 12M6 18L18 6" stroke="#000" stroke-width="2"/>
  </svg>
</button>

<h2>3. svg要素にrole="img"を付与し、svg要素内にtitle要素を入れて代替テキストを設定する</h2>
<button type="button">
  <svg role="img" width="24" height="24" viewBox="0 0 24 24">
    <title>閉じる</title>
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M6 6l12 12M6 18L18 6" stroke="#000" stroke-width="2"/>
  </svg>
</button>

<h2>4. svg要素にrole="img"とaria-labelを付与する</h2>
<button type="button">
  <svg role="img" aria-label="閉じる" width="24" height="24" viewBox="0 0 24 24">
    <path d="M0 0h24v24H0z" fill="none"/>
    <path d="M6 6l12 12M6 18L18 6" stroke="#000" stroke-width="2"/>
  </svg>
</button>
/* Properties are copied from https://tailwindcss.com/docs/screen-readers */
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border-width: 0;
}

h2 {
  font-family: sans-serif;
  font-size: 16px;
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.