Accessible close button displaying X icon
by jorgeluis
HTML
<button class="close" aria-label="Close"></button>
<p>
This was inspired by Sara Soueidan’s post <a href="https://www.sarasoueidan.com/blog/accessible-icon-buttons/">Accessible Icon Buttons</a>
</p>
<p>
Since it’s only specifically for a close "X" icon, it uses css instead of an svg icon. Follow her examples if you need more advanced icons.
</p>
<hr>
<button class="close has-background-fade" aria-label="Close"></button>
<p>
Another option for hover would be to use a background fade, with the biggish advantage that it lets you use transition fade. But this really starts you down the path of what other button color styles your design might use.
</p>
CSS
:root {
--primary: #008094
}
button.close {
padding: 0;
background-color: transparent;
transition: background-color 400ms;
}
.close {
position: relative;
color: var(--primary, blue);
width: 42px;
height: 42px;
border-radius: 42px;
border: 0;
}
.close:hover,
.close:focus {
cursor: pointer;
box-shadow: 0 0 0 1px var(--primary, blue)
}
.close:before, .close:after {
position: absolute;
top: 4px;
left: 20px;
content: ' ';
height: 34px;
width: 2px;
background-color: var(--primary, blue);
}
.close:before {
transform: rotate(45deg);
}
.close:after {
transform: rotate(-45deg);
}
.has-background-fade:hover,
.has-background-fade:focus {
box-shadow: none;
background-color: rgba(0, 130, 150, 0.15);
}
/*
* Utility class to hide content visually while keeping it screen reader-accessible.
* Source: https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html
*/
.sr-only:not(:focus):not(:active) {
clip: rect(0 0 0 0);
clip-path: inset(100%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}