Style a button with hover, focus and disabled states in CSS
15 A button that looks and behaves like one
easyStyle a button with hover, focus, active and disabled states. Use the right element, and make sure it is usable by keyboard.
Stuck? Three hints, smallest first
- 1. Use
<button>. A styled<div>is not focusable and does not fire on Enter or Space. - 2. Never remove the focus outline. Replace it with something clearer if you must.
- 3.
:disabledshould look unavailable and also stop the pointer cursor.
<button class="btn" type="button">Book a seat</button>
<button class="btn" type="button" disabled>Sold out</button>
.btn {
padding: 9px 16px;
border: 0;
border-radius: 6px;
background: #3055d8;
color: #fff;
font: inherit;
font-weight: 500;
cursor: pointer;
transition: background 150ms ease;
}
.btn:hover:not(:disabled) { background: #2544ad; }
/* Replaced, never removed. This is more visible than the browser default. */
.btn:focus-visible {
outline: 2px solid #17171a;
outline-offset: 2px;
}
.btn:active:not(:disabled) { transform: translateY(1px); }
.btn:disabled {
background: #b9bac0;
cursor: not-allowed;
}
10 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('a real button element is used', hasTag(html, 'button'), true);
test('with an explicit type', /type="button"/.test(html), true);
test('there is a hover state', /:hover/.test(css), true);
test('a visible focus state', /:focus-visible/.test(css), true);
test('the outline is never set to none', /outline\s*:\s*none/.test(css), false);
test('an active state', /:active/.test(css), true);
test('a disabled state', /:disabled/.test(css), true);
test('hover does not apply while disabled', /:hover:not\(:disabled\)/.test(css), true);
test('the disabled cursor says so', declares(css, 'cursor', 'not-allowed'), true);
test('font is inherited rather than reset to the browser default', declares(css, 'font', 'inherit'), true);
Output
:hover:not(:disabled) is the detail most button styles miss: without it, a disabled button still lights up under the cursor and looks clickable. font: inherit is the other easy win, because form controls do not inherit typography by default and a button will otherwise render in the browser's own font. And <button type="button"> is deliberate — inside a form, the default type is submit.