A blog post I wrote in 1st year of University (17 October 2020).
There are many ways to format CSS. Formatting is a thing of preference and is down to the individual coder how they like to visually see the code they are writing.
Me? I prefer to have a clear view of the code and be able to manage the styles properly in an organised fashion.
So, let’s have a look at my formatting…
Here is an example of a class declaration.
styles.css
.class {
property: value;
color: #hex
}
Formatting:
{property: value pairs: to separate it from the valueOf course, this is one simple declaration. But it can get a little complicated if formatting isn’t in place.
A lot of the times, there will be multiple selectors combined into one declaration:
styles.css
.class element .class, .class element #id, element[attribute="value"] .class {
}
However, instead of having this jumbled up mess of comma separated selectors, which is a readability concern, it is much better to have a new line for each of the new selectors. Therefore, the start of each new selector is now obvious as they have their own separate line:
styles.css
.class element .class,
.class element #id,
element[attribute="value"] .class {
}
It is very common to indent your code. But how do you indent? What’s the best indentation method?
There are two ways of indenting any kind of code (not just CSS), the space, and the tab. The space is the small whitespace used to separate words (Space-bar key) and tab is the larger whitespace (Tab key). Usually a tab is worth 4 spaces.
Using the space as indentation is ok, but to get equal indentation across the codebase, you have to keep tapping the space-bar to the correct number of spaces of your choosing. This can be good if you want only 1 or 2 spaced indentation, but horrible if you want 4 or more spaces.
This is where tab comes in handy! Tab is used for getting larger whitespace with a single tap of the key. Therefore, making it easier and faster to type the code with indentations.
In modern code editors, we can specify how many spaces one tab is worth, so tab can also be used for smaller or larger amounts of whitespace, depending on the individual’s preference.
I typically use the standard 4 spaces per one tab, as it is neither too small or too large of a whitespace, so you can clearly see the indentations.
In conclusion, it doesn’t really matter how your CSS is formatted as long as you are able to read it properly and understand what is going on. However, for teams or public-use codebase, then it would be wise to adopt a clean approach to format CSS.
This article on CSS Tricks talks about different ways to format CSS and some issues related to do no having good formating.
General rules and guidelines on MDN docs.