Create Custom Keyboard Accessible Checkboxes

Lindsey Kopacz
InstructorLindsey Kopacz

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

In this video we are going to take the native HTML checkboxes and jazz them up while still ensuring they are keyboard accessible. We use pseudo-elements and pseudo-classes to replicate the focus and the ability to tab to custom checkboxes.

Woman: [00:00] Here's our markup, we have a field set and then a legend that just says basic checklist. Then we have three input checkboxes with labels. The first thing we want to do is correct a pseudo element. We would like to create a pseudo element on the label attribute, but only for input type checkbox. Now let's just add the content property, and a width and a height, as well as a background. It looks like we actually need to add some positioning here, so let's do that really quickly.

[00:35] Let's add some positioning to make the label inline and add some padding to give that checkbox some space. Now we have a box and I'm actually leaving the native checkbox there for a reason, just so we can use it for debugging purposes. Now our next goal is to make it obvious when something is checked. When we have this checked, we want something to happen here. We're going to do this using the checked pseudo class.

[01:05] For now, let's just leave it as a background of purple. Now that we've refreshed, if we click on this it should have a purple background. What we're going to do is we're going to create an after pseudo element and create kind of like a rectangle.

[01:35] So this won't look like much right now, but let's just quickly check it out. You can see we have this rectangle when we check the box. There's two primary things that we want to do here. First, we want to take away two of the borders it looks like a checkmark. Then we want to rotate that rectangle. Lastly, I'm going to do some positioning tweaks. Great. I think this looks good.

[02:08] Another ting we have to do is we have to make sure when we press the tab key, so tab, that that box also receives focus. I'm going to add the pseudo class focus on the checkbox to the label of the before element. Now that we have that in, if we press the tab key you can see that both of them have an outline on it. I can also use the space bar to select it.

[02:32] Now that we have this working, the last thing that we are going to do is hide that native checkbox. I'm going to add a position absolute and an opacity of . Now that we've refreshed we can see those checkboxes, and if I press my tab key to tab, you can see that I can select them, and we're good to go.