10 good practices for writing CSS

10 good practices for writing CSS

Writing style sheets doesn’t end with using properties and picking values ​​from a template. This is a voluminous process that includes: Competent naming Structuredness Understandability of selectors Good reusability Compliance with principles of accessibility Optimization
Someone thinks CSS is a simple language, someone is afraid of it, but using the right approaches to writing it will avoid many mistakes. The larger the project, the more complex the CSS looks, and its good support is the work of the layout designer. Only in his power to make the styles can be reused, and the working file itself looks convenient to work with.
In this article, I will talk about my approach to CSS practices and the things that I consider important in development.

Practice 1: organizing the work environment

Writing styles directly to a .css file can come with various problems. A lot of project errors happen due to a forgotten semicolon or an incorrectly closed curly brace. Frequent copying of the same CSS styles also does not bring convenience for future changes.
There are now many tools out there that can automate layout processes and make writing CSS more meaningful. First of all, this is the use of preprocessors. It doesn’t matter what kind of preprocessor you use: SASS, Less or Stylus they allow you to more conveniently remove repetitive CSS, as well as define functions for working with code.
Compare writing the same code using CSS and the SASS preprocessor:

The main difference is the addition of new icons. In the case of CSS, it is necessary to manually add all new icons and, for the correct structure, indicate the new icons next to the old ones. This will require constant navigation through the CSS file, which can be quite large.
In the case of SASS, a mixin was defined that generates an icon depending on the transmitted data and a cycle in which the mixin is called. To add new icons, just change the icons array. The preprocessor will do the rest for us.
Another handy tool is the post processor. If the preprocessor allows you to add new logic to the CSS and eventually compile everything to pure CSS, then the postprocessor works with the already final style file. It allows you to put down all the necessary prefixes, move media queries to the end of the file, and so on. The most popular post processor is PostCSS.
Last but not least, linters are packages that test CSS against standards. This allows you to standardize styles and avoid annoying mistakes. The most popular CSS linter today is Stylelint. It is he who can be seen when taking courses on layout on Hexlet.
Compare the code written without using a linter:
Now the styles are conveniently grouped by the type of properties, and also the indication of the unit of measurement when the value of the margin property is zero has been fixed.

Practice 2: (not) using a framework

CSS framework is a set of modules, components and extensions that can be used in a project. One of the most popular frameworks today is Bootstrap. This is a powerful tool, but you need to understand that loading Bootstrap has a negative impact on the load time of the entire project. Bootstrap 4’s minified stylesheet weighs 156 kilobytes. JavaScript files are also required for this to work.
If only a small part of the framework is needed when using the framework, then it is worth compiling only that part of the CSS that is needed in the project. Bootstrap provides all the SASS files from which you can get only the essentials.
If your project is small, then you should think about whether you need a framework there. Perhaps spending an extra half hour writing your own styles, you will speed up the loading of the site several times.
The other extreme is not using the framework in large projects that are expanding. It doesn’t have to be an open source framework. It can be written internally. This solution will allow you to conveniently reuse components: buttons, unique blocks, forms.

Practice 3: Separating Styles

If you are using preprocessors, use the file import feature. This will avoid storing all the preprocessor code in one single place. In this case, you will end up with the same awkward code to edit as if you were using a single CSS file. Separate parts of your code and create separate files for them. Also create a main file, into which you will include all other files. When compiling, the preprocessor will pull together all the files, and you get one CSS file with all the styles.
SASS example. Main file:
This example smoothly leads to the next point.

Practice 4: variables for project settings

Each project has standard settings that are reused or global. These settings are most often: Color scheme Indentation Font Base font size
Using the preprocessor, you can specify all styles in a single variables or settings file. Now the basic settings will be managed from one file.
Why learn HTML and CSS, or When robots will replace layout designers in the labor market

Practice 5: Reducing Specificity

By decreasing the specificity of the selectors, you not only increase the readability of your code, but also reduce the final size of the CSS file. Take a look at the following example:
It doesn’t seem to have any problems, but in reality it is only tied to a specific HTML structure right now. If it becomes necessary to style another element with these rules, then you need to create a new selector and write styles in it.
By reducing the specificity, you can use the class on any HTML element with any structure.

Practice 6: grouping styles

The article What a layout designer should know about OOCSS and the organization of CSS described one of the most common methodologies OOCSS. It allows you to separate the structural and visual styles of an element. In addition to this separation, the use of methodologies avoids duplicating repeating styles.
A common example:
The example contains styles for two buttons, but they differ in only one property. The rest of the styles are completely repeated. This makes it impossible to quickly change common styles for buttons. The solution is quite simple to allocate a separate class for structural properties.
This technique is available for both CSS and preprocessors. Some methodologies are focused on completely isolating modules from each other. In this case, you can use mixins and variables to create such styles. The main thing is the ability to change properties in one place. This is how it might look in SASS:

Practice number 7: building styles about general to specific

It is good practice to write CSS from general to more specific styles. This means that at the very top, general styles are defined in the form of tag selectors, and after them all the rest. At the same time, the selectors themselves, after the general ones, should be separated into separate sections, such as: General classes (utilities, atomic classes) Classes responsible for the general appearance of the page Classes for various components
Using comments will help you quickly navigate within the CSS file.

Practice 8: Using Inline Styles

Say no to inline styles. They have the highest priority, and their use can greatly interfere with project customization. Most often, inline styles are needed when using JavaScript, when the site responds to user action. For example, with animation. In this case, the use of inline styles is justified.

Practice 9: Adding Focus to Interactive Elements

Layout designers often add new interactive elements that the browser does not know. These can be custom checkboxes, radio buttons, message buttons, and so on. For convenience, they use not standard tags that are intended for such interactions, but simple and . This is where the main danger lies: by styling such elements on hover with: hover, developers forget about users who use keyboards.
These interactive elements may not be available to them, or they simply cannot understand what is on it when using the keyboard. To avoid this error, you should follow a few rules: Whenever possible, use standard HTML elements for interactive elements. Even if these elements do not match the design, try to keep the standard display or make minor changes. Do not remove focus from interactive elements. If such an element is hidden for the sake of customization, add focus for the new elements. Make sure your interactive elements can interact with the keyboard.

Practice 10: naming classes

Don’t forget about good class naming. Ideally, the class name describes what is happening on the page or what block is in front of us. I described this in more detail in the article Naming Errors in Layout. Here’s a small example of bad naming:
In addition to the different types of naming, there is a clear order of the classes. If the HTML elements are swapped, then the whole meaning of such classes will disappear. Determine the name of the class based on what kind of element is in front of you or what characteristics it has. It all depends on the methodology that you follow.