How to write maintainable CSS declarations
Why is the order of the CSS declarations important? Let’s cover the basics first.
A CSS declaration is made up of a selector, or a group of selectors, and a declaration block. Inside of the declaration block, there are declarations with properties and values.
The order of those declarations may seem unimportant at first glance, but defining an order does hold some advantages. An obvious advantage, which is especially important in larger teams, is consistency. Some developers write declarations randomly, some alphabetically, and some group them by type. Grouping is considered to be a good choice because it makes sense to write the positioning-related declarations first as some elements could be removed from the flow. The browser digests it first, and the developer can read the block with ease knowing where the element will be positioned right away. Like the Bootstrap creator Mark Otto, Toptal CSS developers have found the following order of styles easy to maintain:
- Positioning
- Box model
- Typographic
- Visual
Here is a general example:
.declaration {
/* Positioning */
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 100;
/* Box-model */
display: block;
float: right;
width: 100px;
height: 100px;
/* Typography */
font: normal 16px Arial, sans-serif;
line-height: 1.5;
color: #333;
text-align: center;
/* Visual */
background-color: #fff;
border: 1px solid #eee;
border-radius: 5px;
}
For developers using a CSS preprocessor, the best practice is to write @extend
rules first and @include
rules second. The reason for that is the fact that you’re aware right away that those styles are inserted into the selector, and you are able to easily override them below it.
Contributors
Bojan Janjanin
Bojan is a senior web designer with development skills and over 15 years of professional experience—covering a wide range of projects, tools, and techniques. Bojan specializes in creating usable, user-centered web and mobile solutions. Where Bojan really shines is crafting UI designs through the lens of UX.
Show More