Back in December 2021, I wrote an article titled "Defensive CSS". I used that term because that's really what is it about. I wanted a term that communicates clearly the concept of writing CSS that prevent unexpected layout behaviors, or at least, reduce them.
So, what is defensive CSS?
a set of CSS practices and techniques that designers and developers can use to write CSS that is future-proof, resulting in less bugs in user interfaces.
It turned out that defensive CSS doesn't only apply to CSS, but to UI design as well. As a designer, you need to either work on a visual variations of a component with all the possible use-cases, or at least to communicate them clearly with the development team.
In this introduction article, I will shed the light on why it's important to design and write CSS defensively, and how we can take it from there.
The problem
To explain why designing and coding defensively is useful, I will share a simple example. In the following figure, we a list of features. Each feature item has a tick icon on the left side.
/assets/intro-1-1.png
When the title isn't wrapping into a new line, it looks fine and everything is aligned. However, when the title gets a bit longer, it will wrap around the icon, resulting an a misaligned design.
/assets/intro-1-2.png
The above problem happened because we didn't account for what should happen when the content is long, or wrapping into a new line.
The solution
To fix the previous problem, we need to account for it in advance. In other words, we need to imagine having the problem and fixing it right away.
This is what defensive CSS is about. Accounting for edge cases and writing CSS that prevent them.
Given that we have a list component, we can add display: flex
by default and it will help prevent the issue.
.list-item {
display: flex;
}
.list-item__icon {
flex: 0 0 16px;
width: 16px;
height: 16px;
margin-right: 0.5rem;
}
Here is a before and after comparison.
/assets/intro-1-3.png
It's not only about CSS
I think that web designers can also participate in this. When a designer provide a developer with how a component should behave under different situation, it will save up a lot of time and effort.
- Designers: how to design defensively?
- Figma truncation.. ?