Stop using % on your CSS!
CSS Pet Peeve
I realized this topic is very subjective, but looking back 6 years that I’ve dealt with CSS I think I have some right to say about this topic. Before you start raging in the comment section on why it’s okay to use percentage, there are some special cases though where it’s acceptable to use percentage .
The reason I want to talk about this: I’ve reviewed a lot of Pull Requests lately and I was reminded that a lot of engineers using percentage where it’s not supposed to. And as you guessed already by the title, it’s one of my pet peeves looking at people using percentage without a good understanding why they should or should not be using percentage.
Instead of me explaining why shouldn’t be using percentage, let me give you real code example where people tend to make mistakes. I will cover most of the major cases where engineers are using percentage in the wrong place.
Common mistakes in React Bootstrap
Imagine you need to implement 2 buttons on 1 row where each button takes half of the space given on that row. Here’s the common mistakes that a lot of engineers do.
Now here’s the better approach.
Looks very similar? Indeed. Both have the same approach, but the first approach doesn’t utilize the grid system. Why is it wrong then? Well, once you’re using the grid system, you should honor the system and bound to it, if you’re not, then it’s a question back to you: why are you using the grid system then?
Common mistakes in Vanilla CSS
Now here’s another common mistake that engineers do. Setting up a button width that is percentage to its parent’s width.
Looks okay to you? Try squeezing the screen until you see this.
The problem is when you don’t set a minimum width for your the parent container (or using adaptive strategy), you will mostly ended up with the picture on the left.
The text is overflowing because the width of the button is set to 20% of the current screen size, resulting the text inside the button to overflow.
The right solution is to not use the percentage as the title suggests. From the design perspective, either you have a fixed width with a limited text, or you make it a flexible with (following the content of the button) with some padding. Both approaches are valid; really based on how the designer has intended the button to be.
So why do we have percentage in the first place? And when are we allowed to use it?
In the old days where we don’t have grid system, one of the solutions to keep everything align perspectively with the current container width is by using percentage. Here’s one real example where design requires element to act using percentage.
Conclusion
Hopefully it’s pretty clear by now where you should or should not be using percentage on your CSS. It’s mostly around the context — if you are using grid or not — and the goal of the element when using the percentage, especially when you have to build the element inside a variable container width or responsive design.