January 22, 2018Writing better CSS
Writing better CSS
Writing CSS can be hard, but writing great CSS as a large team can seem impossible. So what can we do about it? Well, similar to javascript CSS has seen some incredible growth in the tooling available. By taking some time to understand a few of the common problems we can then evaluate the potential solutions. This post will cover a few of what I feel to be the most common issues I’ve come across.
The “bones” are too rigid
When Bootstrap came along in mid-2011 it caught on rather quickly. It was a very well-thought-out CSS Starter Kit. You needed a grid and it made it easy to do, it was responsive, and even knowing very little CSS you could drop this into a web page, sprinkle some classes, and have a pretty decent-looking site with very little effort. The problem here tends to be a result of implementation and time. As soon as we customize the vendor’s code (bootstrap source), we’ve made it increasingly difficult to update down the road. The solution here is to introduce a sort of intermediary file to call in the vendor code and introduce the necessary overrides in between. Take this example:
Selectors are too specific
LESS and SASS have become an essential tool for any Front End developer. They give us functions, mixins, nesting, variables and much more. But, more times than not I find myself jumping into a file only to find CSS’s version of callback hell which takes the form of deep nesting and sprinkled mixins.
A simple example:
.wrapper .scoped-area {
ul {
li {
a {
color: red;
&:hover {
color: green;
}
}
}
}
}
.wrapper .scoped-area ul li a {
color: red;
}
.wrapper .scoped-area ul li a:hover {
color: green;
}
It was more work to make the example than it would have been just to write this out. Also, out of the box, we are starting to build some bad habits. As we continue to iterate the nesting only becomes more complex, the selectors become more complex slowing down paint and our file sizes increase. It’s a 3 pronged knock.
Avoid Repetition
Now that we have access to CSS variables theres really no excuse to no abstract your color palette and font families into something manageable.