Formatting Your CSS Code
๐ก
Essential Question: What are best practices for formatting CSS code?
You may have noticed some patterns when we were writing CSS in the last lesson where broke down the CSS syntax. CSS is a very forgivable language because if you make a mistake, it simply ignore that part of the code and moves on. Other languages are more prone to completely breaking things if there’s even so much as a minor typo.
/* This ruleset is ignored */
.some-element {
colour: #f8a100; /* Should be `color` */
}
Even though it’s tough to “break” CSS, there are still some best practices when it comes to writing it which is what we’re covering in this lesson.
Mind Your Punctuation
Remember that all property:value combinations go inside curly brackets:
.selector {
/* Styles go here! */
}
And when writing a property:value combination, each one is followed by a semicolon:
.selector {
background-color: #000;
color: #fff;
}
It’s important that your properties and values are inside the curly brackets so your styles are properly related to the selector. It’s equally important to use a semicolon after a property:value combination to separation one combination from another.
One Property:Value Pair Per Line
It’s much easier to read CSS when the properties are on individual line. Even the simple example above is harder to read on a single line:
/* ๐คฎ */
.selector { background-color: #000; color: #fff; }
I feel the same way about selectors. As you’ll learn in an upcoming assignment, it’s possible to chain multiple selectors together to apply the same styles to them, as long as they’re separating by commas. I think it’s easier to read a list of selectors in a ruleset if they are also written on individual lines.
.selector-1,
.selector-2,
.selector-3 {
/* Styles would go here. */
}
Alphabetize Your Properties
This is totally my personal preference. Every developer has a different way of organizing the properties in a ruleset. I like the idea of listing them in alphabetical order because you know what to expect when you start reading through a CSS file. But what I care about most is that you have a system for organization. Writing properties all willy-nilly is a recipe for errors.
.selector {
/* Alphabetical order! */
background-color: #000;
border-radius: 16px;
color: #eaeaea;
display: flex;
font-size: 1.5rem;
justify-content: center;
line-height: 1.35;
position: relative;
z-index: 1;
}
Indent properties inside the ruleset instead of having all your CSS line up like this:
.selector {
background-color: #000;
border-radius: 16px;
color: #eaeaea;
}
…put at least two spaces before the properties to let things breath a little easier:
.selector {
background-color: #000;
border-radius: 16px;
color: #eaeaea;
}