The Benefits of Structuring CSS Around Appearance and Layout
I like this point that Jonathan Snook made on Twitter and I’ve been thinking about it non-stop because it describes something that’s really hard about writing CSS:
I feel like that tweet sounds either very shallow or very deep depending on how you look at it but in reality, I don’t think any system, framework, or library really take this into consideration—especially in the context of maintainability.
— Snook (@snookca) February 26, 2019
In fact, I reckon this is the hardest thing about writing maintainable CSS in a large codebase. It’s an enormous problem in my day-to-day work and I reckon it’s what most technical debt in CSS eventually boils down to.
Let’s imagine we’re styling a checkbox, for example – that checkbox probably has a position on the page, some margins, and maybe other positioning styles, too. And that checkbox might be green but turns blue when you click it.
I think we can distinguish between these two types of styles as layout and appearance.
But writing good CSS requires keeping those two types of styles separated. That way, the checkbox styles can be reused time and time again without having to worry about how those positioning styles (like margin, padding or width) might come back to bite you.
At Gusto, we use Bootstrap’s grid system which is great because we can write HTML like this that explicitly separates these concerns like so:
<div class="row">
<div class="col-6">
<!-- Checkbox goes here -->
</div>
<div class="col-6">
<!-- Another element can be placed here -->
</div>
</div>
Otherwise, you might end up writing styles like this, which will end up with a ton of issues if those checkbox styles are reused in the future:
.checkbox {
width: 40%;
margin-bottom: 60px;
/* Other checkbox styles */
}
When I see code like this, my first thought is, “Why is the width 40%
– and 40% of what?” All of a sudden, I can see that this checkbox class is now dependent on some other bit of code that I don’t understand.
So I’ve begun to think about all CSS as fitting into one of those two buckets: appearance and layout. That’s important because I believe those two types of styles should almost never be baked into one set of styles or one class. Layout on the page should be one set of styles, and appearance (like what the checkbox actually looks like) should be in another. And whether you do that with HTML or a separate CSS class is up for debate.
The reason why this is an issue is that folks will constantly be trying to overwrite layout styles and that’s when we eventually wind up with a codebase that resembles a spaghetti monster. I think this distinction is super important to writing great CSS that scales properly. What do you think? Add a comment below!
The post The Benefits of Structuring CSS Around Appearance and Layout appeared first on CSS-Tricks.