Why you should use flexbox for more maintainable buttons (and other components).


In short, your components can be explicitly sized with their contents dynamically placed.

Slow down there son! What?

Let’s make a button. Just a simple one using some simple CSS.

.button {
    padding: 8px 12px;
    background-color: lightblue;
    color: blue;
    border-radius: 6px;
}

Not very pretty, but just enough to get the idea of a button on the page.

Question: What’s the height of the button?

Answer: Not sure without a bit of inspecting.

You need to consider font size and line-height, and then you need to add on the padding.

It’s not terrible, but the height of your button is being defined by other factors not directly relevant to the button.

There is a better way:

.button {
    display: flex;
    align-items: center;
    height: 20px;
    padding: 0 12px;
    background-color: lightblue;
    color: blue;
    border-radius: 6px;
}

Instead we use flexbox. It lets us easily vertically center the content of the button while setting an explicit height (20px).

Why is this good? We are defining our button height directly. We now know exactly how our buttons interact with the space on our page. For web pages in general, this is good. For app user interfaces, it’s even better. It gives us clarity and control.

Buttons are an easy example, but it works for so many other components.


Leave a Reply

Your email address will not be published. Required fields are marked *