March 09, 2022

How to make a button

Writing a good button for your website doesn't need to be hard, this post will show you the way!

How to make a button

It feels like making a reusable button that works for everything should be easy, but if you have never made one or if you've never had time to think while build one from scratch; they can be a pain to maintain.

Over the next four blog posts, we will dig into the ins and outs of what it takes to build a reusable button that is sure to scale with the ever-increasing needs of your project as it matures. But what we learn here need not be used in isolation; there are plenty of other instances in which you want a component to work for any semantical element, and you can use the same principles there.

Before we start, here is the result that we are working towards:

/* define default button theme on root */
:root {
--btn-color: #FFFFFF;
--btn-background-color: #EA4C89;
--btn-background-color-hover: #F082AC;
}
/* normalise base element */
.anchor-btn {
display: inline-block;
text-decoration: unset;
color: var(--btn-color);
}
.button-btn {
display: inline-block;
background: none;
border: none;
padding: 0;
font: inherit;
color: var(--btn-color);
}
/* button styling */
.btn {
background-color: var(--btn-background-color);
border-radius: 8px;
font-size: 14px;
font-weight: 700;
line-height: 20px;
padding: 10px 16px;
text-align: center;
transition: color 100ms;
vertical-align: baseline;
cursor: pointer;
}
.btn:focus, .btn:focus-visible {
outline: 2px dotted #999;
outline-offset: -2px;
}
.btn:hover {
background-color: var(--btn-background-color-hover);
}
/* customised buttons */
.btn.btn-green {
--btn-color: #232323;
--btn-background-color: #5cdb5c;
--btn-background-color-hover: #7ce27c;
}

If you look at the comments in the css, you can see the three critical parts of designing reusable and consistent buttons that work for any HTML elements. Those steps consist of:

  1. Normalise the element to look like an un-styled span of text.
  2. Apply button styling
  3. Apply customisation for the individual button (as such as colour)

We split the styling up into these three stages for ease of development and assurance that our buttons will look correct no matter what elements we end up utilising for the button. Using the right element for the button, be it input, button, OR anchor, is hypercritical if you want to build a website that the user's browser and accessibility tools can understand. It's not acceptable to have a button with an onclick event that triggers a route change, you should be giving your users an anchor tag, and it shouldn't look any different.

Next Up: part 2 - normalisation

Tagged with css, design, html, --css-variables

something not right? Open a PR