• 10 Best Practices for Improving Your CSS
  • Ferenc Almasi
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: febrainqu
  • Proofreader: Rachelcdev, LHD951220

10 best practices for improving CSS

CSS seems like a very straightforward and fallible language. You just need to add rules to style your site, right? This may be the case for small sites that only need a few CSS files. But in large programs, this can quickly get styles out of control. How do you make them more manageable?

The truth is, just like any other language, the nuances of CSS can make all the difference in your design. Here are 10 TIPS for CSS – best practices that can help you get the most out of your styling.

Do you really need a framework?

First, determine if you really need to use a CSS framework. There are many lightweight alternatives to heavy frameworks. Often, you won’t use every selector in the framework, so your programs will contain redundant code.

If you only need to use the button styles, copy them into your own CSS file and delete the rest. In addition, you can use code coverage detection in developer tools to identify unused CSS rules.

To open it, search for Coverage in the Tools panel. You can open the tools panel by clicking Ctrl + Shift + P. Once opened, click the reload icon to start recording. All content shown in red is unused.

As you can see in the example above, it shows that 98% of the CSS is unused. Note that this is not the case — some CSS styles are applied only after the user interacts with the site. Mobile device styles are also marked as unused. So before you delete everything, make sure that these styles are really not used anywhere.

2. Select a CSS specification

Consider using a CSS specification for your project. The CSS specification makes CSS files consistent. They help extend and maintain your project. Here are some CSS specifications that I recommend.

BEM

BEM — Block, Element, Modifier — is one of the most popular CSS specifications. It is a set of naming conventions that you can use to easily design reusable components. The naming convention follows the following pattern:

.block { ... }
.block__element { ... }
.block--modifier { ... }
Copy the code
  • .blockA: block represents a component. They are separate entities and have meaning for themselves.
  • .block__elementThese are:.blockPart of. They have no independent meaning and must be bound to a block.
  • .block--modifier: They are used as markers for blocks or elements. We can use them to change the appearance, behavior, or state of elements. For example, to use a hidden tag, we could name it.block--hidden.

ITCSS

Inverted triangle CSS helps you better organize your files by introducing different layers to implement different features. The deeper you go, the more specific you get.

OOCSS

Object-oriented CSS or OOCSS follows two main principles.

Separate structure and visuals

This means that you define visual effects separately from structural code. What does this mean in practice?

/* Content to be optimized */
.box {
    width: 250px;
    height: 250px;
    padding: 10px;
    border: 1px solid #CCC;
    box-shadow: 1px 2px 5px #CCC;
    border-radius: 5px;
}

/* Optimized */
.box {
    width: 250px;
    height: 250px;
    padding: 10px;
}

.elevated {
    border: 1px solid #CCC;
    box-shadow: 1px 2px 5px #CCC;
    border-radius: 5px;
}
Copy the code

Separate containers and content

This means that you don’t want any element to depend on its position. The same elements should look the same no matter where they are on the page.

/ /.main span. Breadcumb {... } /* Optimized */. Breadcrumb {... }Copy the code

3. Set the preprocessor

Setting up a preprocessor can benefit you in a number of ways. A preprocessor is a tool that allows you to use advanced features that don’t exist in CSS. These features could be things like loop variables or even functions.

There are a lot of preprocessors out there. The three most famous are probably Sass, Less and Stylus. I recommend using Sass because it has an established community and you can find plenty of documentation about it online.

So what can the preprocessor do to help?

Organize styles better

Preprocessing can help you organize your styles better. They can break down your files into smaller reusable files. They can be imported into each other or into your application separately.

// Import different modules for an SCSS file
@import 'settings';
@import 'tools';
@import 'generic';
@import 'elements';
@import 'objects';
@import 'components';
@import 'trumps';
Copy the code

Nested selectors

Another great way to enhance readability is to nest selectors. This is a simple and powerful feature that CSS lacks.

.wrapper {
    .sidebar{&.collapsed {
            display: none;
        }
        
        .list {
            .list-item{... &.list-item--active{... } } } } }Copy the code

The hierarchical structure allows us to see more clearly the combination of different elements.

Automatically prefix your rules

CSS has prefixes for non-standard or experimental features. Different browsers use different prefixes for this, for example:

  • -webkit-: Works with webKit-based browsers, such as Chrome, Safari, or newer versions of Opera.
  • -moz-: Applies to Firefox.
  • -o-: Works with older Opera versions.
  • -ms-: For Internet Explorer and Edge.

To support all major browsers, we had to define certain properties multiple times.

.gradient {
    background: rgb(30,87,153);
    background: -moz-linear-gradient(top, rgba (30,87,153,1)0%.rgba(41137216, 1)50%.rgba(32124202, 1)51%.rgba(125185232, 1)100%);
    background: -webkit-linear-gradient(top, rgba (30,87,153,1)0%.rgba(41137216, 1)50%.rgba(32124202, 1)51%.rgba(125185232, 1)100%);
    background: linear-gradient(to bottom, rgba (30,87,153,1)0%.rgba(41137216, 1)50%.rgba(32124202, 1)51%.rgba(125185232, 1)100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#1e5799', endColorstr='#7db9e8', GradientType=0);
}
Copy the code

The preprocessor solves this problem by making use of mixins — functions that can be used instead of hard-coded values.

@mixin gradient() {
    background: rgb(30.87.153);
    background: -moz-linear-gradient(top, rgba(30.87.153.1) 0%, rgba(41.137.216.1) 50%, rgba(32.124.202.1) 51%, rgba(125.185.232.1) 100%);
    background: -webkit-linear-gradient(top, rgba(30.87.153.1) 0%, rgba(41.137.216.1) 50%,rgba(32.124.202.1) 51%, rgba(125.185.232.1) 100%);
    background: linear-gradient(to bottom, rgba(30.87.153.1) 0%, rgba(41.137.216.1) 50%,rgba(32.124.202.1) 51%, rgba(125.185.232.1) 100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#1e5799', endColorstr='#7db9e8', GradientType=0);
}

.gradient{@include gradient();
}
Copy the code

Adding mixins when needed avoids writing redundant code.

Post-processor

A better choice is the post-processor. Once the CSS is generated by the preprocessor, the post-processor can run other optimization steps. One of the most popular post-processors is [PostCSS](https://postcss.org/).

You can use PostCSS to automatically prefix CSS rules without worrying about missing major browsers. They Use values from Can I Use so it is always up to date.

Another good after the processor is [autoprefixer] (https://www.npmjs.com/package/autoprefixer). With AutopreFixer, when you want to support the latest four releases – you can do it all without having to write any prefixes in your CSS file!

const autoprefixer = require('autoprefixer') ({browsers: [
	'last 4 versions'.'not ie < 9']});Copy the code

Design consistently using configurations

In addition to mixins, you can also choose to use variables. With Linter, you can enforce your own design rules.

// Font definition
$font-12: 12px;
$font-21: 21px;

// Color definition
$color-white: #FAFAFA;
$color-black: # 212121;
Copy the code

4. Use labels instead of CSS

Now let’s get into the actual CSS application. This is often overlooked. In general, you can reduce the size of CSS packages simply by using the correct HTML tags. Suppose your title contains the following rules:

span.heading {
    display: block;
    font-size: 1.2 em;
    margin-top: 1em;
    margin-bottom: 1em; 
}
Copy the code

You used a SPAN tag for the title. You rewrote the default display, spacing, and font styles. This can be avoided by using H1, H2, or H3. By default, they have the style you are trying to achieve with other tags. You can immediately eliminate four unnecessary style rules.

5. Use shorthand properties

To further reduce the number of style rules, shorthand attributes are often used. For the above example, we could write:

.heading {
    margin: 1em 0;
}
Copy the code

The same is true for other attributes, such as borders, borders, or backgrounds.

6. Reduce redundancy

This is closely related to the previous point. Redundancy is sometimes difficult to find, especially when the repeating rules in the two selectors do not follow the same order. However, if your class differs only in one or two rules, it is best to outsource those rules and use them as an additional class. Here is the code before optimization:

<style>
    .warning {
        width: 100%;
        height: 50px;
        background: yellow;
        border-radius: 5px;
    }

    .elevated-warning {
        width: 100%;
        height: 50px;
        font-size: 150%;
        background: yellow;
        box-shadow: 1px 2px 5px #CCC;
        border-radius: 5px;
    }
</style>

<div class="warning">⚠ ️</div>
<div class="elevated-warning">🚨</div>
Copy the code

Try a similar approach:

<style>
    .warning {
        width: 100%;
        height: 50px;
        background: yellow;
        border-radius: 5px;
    }

    .warning--elevated {
        font-size: 150%;
        box-shadow: 1px 2px 5px #CCC;
    }
</style>

<div class="warning">⚠ ️</div>
<div class="warning warning--elevated">🚨</div>
Copy the code

7. Avoid complex selectors

There are two main problems with using complex selectors. First, the added features not only make it more difficult to rewrite existing rules later, but also increase the time it takes for the browser to match the selector.

Match selector

As the browser parses the selector and determines which element it matches, they proceed from right to left. In terms of performance, this is faster than the reverse. Let’s take the following selector as an example.

.deeply .nested .selector span {
    ...
}
Copy the code

The browser will start with span. It will match all span tags and then move on to the next match. It filters out the span in the.selector class, and so on.

CSS tag selectors are not recommended because they match all tags. It’s only a fraction of a millisecond, but it all adds up. Another, more important reason is that it’s good practice to reduce selector complexity.

Understanding selector

Not only are machines hard to parse, but humans are also hard to understand. Take the following example:

[type="checkbox"]:checked + [class$="-confirmation"]::after {
    ...
}
Copy the code

When do you think the above rules apply? You can simplify this process by creating custom classes and switching them using JavaScript.

.confirmation-icon::after {
    ...
}
Copy the code

It looks much more comfortable now. If you find yourself still needing an overly complex selector, and you believe there is no other option, please leave a comment explaining your solution below.

/** * Select the check box to create a confirmation icon. * Select all labels ending with the class name "-confirmation" * there is a selected check box in front of it. * PS. : There is no other way to solve this problem, please do not try to fix it. **/ .checkbox:checked + label[class$="-confirmation"]::after { ... }Copy the code

8. Don’t delete the outline

This is one of the most common mistakes developers make when writing CSS. While you may think there is nothing wrong with removing the highlighting created by the contour, in fact, you are making the site inaccessible. This rule is usually added as a CSS reset value.

:focus {
    outline: none;
}
Copy the code

However, users who can only navigate with a keyboard will have no idea where or what the site focuses on.

If the default style is not good for your brand, create custom contours. Just make sure you have some indication of the focus element.

9. Use mobile devices first

Always use a mobile device first when you must deal with media queries. The mobile-first approach means that when you start writing CSS, you need to start with small screen development and then expand to other devices. This is also known as progressive enhancement.

This will ensure that you mainly add additional rules to cater to larger screen devices, rather than rewriting existing CSS rules. This reduces the number of rules you end up using.

How do you determine whether to use mobile first? If your media query uses min-width, you are on the right track.

/* Mobile first media query, all devices above 600px will get the following style */
@media (min-width: 600px) {
    /* Your CSS rules */
}

/* Non-mobile first media query, all devices below 600px will get the following style */
@media (max-width: 600px) {
    /* Your CSS rules */
}
Copy the code

Compressed 10.

Finally, compress file packages to reduce their size. Because the compression process removes comments and whitespace characters, file packages can be obtained with less bandwidth.

If not, you can also enable compression on the server side.

Another good way to further reduce the size of CSS — and tags — is to obfuscate class names.

To do this, you can select several options based on your project Settings:

  • Webpack: For Webpack, this is available[css-loader](https://github.com/webpack-contrib/css-loader)The module.
  • Gulp: For Gulp, it can be used[gulp-minify-cssnames](https://www.npmjs.com/package/gulp-minify-cssnames)The plug-in.
  • Customization: If you don’t have a dedicated package for your project setup, I’ll provide a tutorial that shows you how to create your own implementation.

conclusion

Following these 10 simple steps will help you write CSS files that have the following advantages:

  • lighter
  • Easy to maintain
  • extensible

Not only that, but using some utilities, such as predefined color palettes or typography rules, will help you create more stable designs. Your style will also be more reusable, and you’ll save time on your next project.

What other CSS best practices do you follow that haven’t been covered in this article? Let us know in the comments!

Thank you for taking the time to read this article and have a great day!

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.