Cognitive biases

When we come across a plan or idea that is different from our own cognition, emotional likes and dislikes are definitely in front of us, which is our instinct. If you don’t like someone, it’s hard for you to notice his good points, while if you like someone, you will ignore his bad points.

As much as I didn’t like BEM in the first place, I found it made my CSS names long and smelly. When I settle down to think about the problem it’s trying to solve, I know how biased I am.

Any proposal must address a pain point. It is suggested to put personal preferences behind first and think calmly about what problems this program should solve. Chances are the solution isn’t bad, but it doesn’t address your pain points, that’s all.

Of course, this article is intended to share an opinion with you, so please bear with me. 😄

You shouldn’t abbreviate

When we learn any computer language, we are required to have readable names. In native JS, for example, we see names like this:

  • getElementById
  • getElementsByClassName
  • getElementsByName

Basically, we know what this is all about, but if you notice someone naming it something like this:

  • getEId
  • getECN
  • getEN

I’m sure you’re like me when you first see code like this, there’s a big question mark in your head, and getEId can probably guess what it’s about. But getEN I might think this is a way to translate Chinese into English.

Therefore, it is common practice not to use abbreviations when naming, and to write as much as possible, even if it will increase the size of the code, but it is recommended for project management.

However, when writing CSS, I find that this rule can be loosened a little bit.

When do we choose to abbreviate?

In order not to draw a conclusion and cause resistance, let me talk about under what circumstances do we choose to abbreviate?

  • In life: KPI, IOS, CEO, Live long see…
  • H1, em, a, br…
  • JS: var, let, $, _…

To sum up, we will use abbreviations for the convenience of using phrases that are very common in certain contexts.

Taking our previous JS environment for example, getElementById, if you only used it 10 times or so during our actual development, I don’t think you would have thought about abbreviating it.

But when you find yourself using it hundreds or thousands of times, even if your editor, when you type get, conjures up getElementById for you, you’ll still consider giving the word a shorter name. Like this:

function $(id){
    return document.getElementById(id);
}
Copy the code

Simply put, we want abbreviations that appear too often.

Semantic CSS should not be abbreviated

In the CONTEXT of CSS, I believe the word you hear most about naming is semantic.

One thing I admire about CSS semantics is zen gardens. The author just writes a DOM structure and some CSS class names, and then hundreds of people can write pages that look completely different from the author based on those CSS class names without changing the DOM structure at all. It’s like a skin change, a perfect separation of structure and style.

So again, I strongly discourage abbreviations for semantic naming.

So what are the alternatives to semantic CSS naming?

This is a question I believe most front-end developers have a hard time answering. After many years in the business, I’ve found that my belief in the semantics of CSS is the root cause of my inefficiency in CSS writing. Because naming is a time consuming thing. Check out my other CSS-related article, “How to Manage CSS Panties.”

Based on the point that CSS class names can be abbreviated, I gave the answer ACSS (Atomic CSS), of course, it is very inaccurate to say that ACSS is a naming method.

If you’re not comfortable with the idea of ACSS at the moment, it doesn’t solve your pain points at work. Spend the time playing video games or talking to girls, and forget about the rest.

Why can ACSS be abbreviated

ACSS is, as its name suggests, atomized CSS. Is to break down the styles of CSS to the atomic level.

Simply put, a single line of code for a name, and a single line of code for a style, doesn’t that sound particularly consistent with the single charge of design patterns?

semantic

.main-title{
    font-size:24px;
    line-height:32px;
    color:$color_primary;
    font-weight:700;
}
Copy the code
<h2 class="main-title">That's the main heading</h2>
Copy the code

ACSS

.fontSize24{ font-size:24px; }
.lineHeight32{ line-height:32px; }
.colorPrimary{ color:$color_primary; }
.fontWeight700{ font-weight:700; }
Copy the code
<h2 class="fontSize24 lineHeight32 colorPrimary fontWeight700">That's the main heading</h2>
Copy the code

Semantic Class and ACSS Class, the probability of reuse is basically not of an order of magnitude. Take the example above, a page with 10. Main-titles is already a very complex page. There is a limit to how many times it can be reused, even on the whole site.

Some ACSS Class names are much more likely to be reused, even on a single page, than semantic classes. Such as the font – size: 14 px; It’s not uncommon to be reused hundreds of times in a single project.

So the core of ACSS class names that can be abbreviated is that ACSS class names are reused too many times.

How to abbreviate CSS?

One of the core arguments against class names not being abbreviated is the rule on how to define abbreviations. Different people have different abbreviations.

Let’s first look at how well-known solutions define abbreviations.

@bootstrap v4

{
    "bg-primary":"background-color:$primary;"."p-*":"padding: * ;"."m-*":"margin: * ;";
    "d-inline":"display: inline;"."sm":"small"."md":"middle"."col":"column"."btn":"button"."w-":"width:*;"
    / *... * /
}
Copy the code

@material-ui

{
    "bgcolor":"backgroundColor"."zIndex":"z-index"."p":"padding"."m":"margin"."sm":"small"."md":"middle"
    / *... * /
}
Copy the code

@Zhang Xinxu teacher

{
    "dn":"display:none;"."b":"font-weight:bold;"."cl":"clear:both;"."ovh":"verflow:hidden;"."ml10":"margin-left:10px;"
}
Copy the code

See here, you are as messy as I am. Which ones can be abbreviated? Is it a hyphen or a slide or a case?

But the reason we’re messed up is because we’re not on these projects. We did not write padding for hundreds of times in the Material UI project, nor did we write margin for more than thousands of times in the bootstrap project, nor did we have more than 10 years of page writing experience like Teacher Zhang. So it’s easy to have some established logic.

Over the years, I also maintain such an enumeration map. But I have to admit that enumeration mapping is pretty high for beginners. “Your honey, second arsenic” is such a truth.

In order to solve this problem, I spent a lot of time, trying, the following is my current conclusion (basically in the logic of teacher Zhang’s second encapsulation).

@my plan

  1. First letter only:.db{ display:block; };
  2. There are digital direct connections:.mb10{ margin-bottom:10px; };
  3. A dash indicates a negative number:.mb-10{ margin-bottom:-10px; };
  4. Percent in%Said:.w100\%{ width:100%; };
  5. The decimal point with.Said:The lh1 \. {5 line - height: 1.5; };
  6. Join parameters (not allowed to abbreviate) are underlined:.c_primary{ color:$primay; };
  7. Do not abbreviate or use conventional names for non-ACSS:.clearfix{ };

Special symbols need to be escaped in CSS, but not in HTML.

Unlike other enumerated maps, mine is held together by this naming convention.

In short, it’s much easier to remember the naming rules than it is to remember the entire mapping list.

And naming rules reduce the chance of confusion during development. For example, if I need a background color, if I don’t have a naming rule, I need to check the mapping table to see if it is bgColor like material or BG – like bootstrap. If you had a clear naming convention you would know it’s BC because it’s just the first letter.

Having a naming convention also makes it easier for others to add common classes to it, rather than relying on personal habits. Of course, it’s hard to convince different people to define the same set of rules, so I can only say “go with the flow.”

<div class="pt16 pl16 pr16 pb16">
  <h3 class="fs16 lh24 fw700 mb4">Atomic css</h3>
  <p class="fs12 lh20">The development experience of Atomic CSS is fantastic and super fast.</p>
</div>
Copy the code
<style>
    .card{ padding: 16px; }
    .title{ font-size:16px; line-height:24px; font-weight:700; margin-bottom:4px; }
    .content{ font-size:12px; line-height: 20px; }
</style>
<div class="card">
  <h3 class="title">Atomic css</h3>
  <p class="content">The development experience of Atomic CSS is fantastic and super fast.</p>
</div>
Copy the code

While others are still trying to decide whether to call the container card or box, your code is already written. As you get used to the whole naming convention, you get the illusion during development that you want a certain style and then your code is done. This is great for the development experience.

Of course, my plan is not perfect, and some corners and corners cannot be completely covered, but basically there is no problem with the basic style of daily life. If you have a naming scheme with fewer rules than mine, please share it with me.

If you use the Emmet plugin, you’ll find that you can even write CSS properties using abbreviations and TAB completion. Of course, my rules are a little different from Emmet’s, but they don’t affect actual use.

A style library for custom projects

The ACSS map has a great relationship with the atomic design materials of the design students, and even should be consistent. For example, if all of your project A’s spacing is developed on multiples of 5, your mapping table should have:

.mb5{ margin-bottom: 5px; }
.mb10{ margin-bottom: 10px; }
.pt10{ padding-top:10px; }
.pb10{ padding-bottom: 10px; }
/ *... * /
Copy the code

For your project B, all spacing is developed on multiples of 4, so your mapping table should not have the logic of multiples of 5 above, but instead:

.mb4{ margin-bottom: 4px; }
.mb8{ margin-bottom: 8px; }
.pt4{ padding-top:4px; }
.pb8{ padding-bottom: 8px; }
/ *... * /
Copy the code

If you think it’s too much trouble to write this every time you start a new project, you can recommend our Mixin libraries, less and Sass both have SACSS.

For those of you familiar with style-system, you may notice that we do not use multiple logic similar to style-system for spacing (this logic is used for material- UI and bootstrap).

$margins: [4px.8px.16px.24px.32px];
.mb-1{ margin-bottom:$margins[1]; }
.mb-2{ margin-bottom:$margins[2]; }
.mb-3{ margin-bottom:$margins[3]; }
.mb-4{ margin-bottom:$margins[4]; }
/ *... * /
Copy the code

In short, we find this unintuitive. And if we had to increase the spacing by 20px, our entire logic would have been broken and the class named MB-3 would have to be named MB-4.

However, the actual plan is often unable to catch up with the change, so it is better to directly use the numbers to direct and simple, in the development of the need not to think. Mb4 is margin – bottom: 4 px; $margins[4], the $margins array is short.

Styles go beyond CSS

This article has been all about CSS, but what I really want to say is that styles can try to consider ACSS, and then the ACSS place can try to consider abbreviations.

Style to write more students will know that common styles come and go also that a few, nothing more than to adjust their permutations and combinations. I feel like I’m reinventing the wheel every time I write this repetitive style code.

With JS growing like crazy, CSS-in-JS is also glowing. But that doesn’t affect our whole logic. Take the famous emotion for example.

import react from 'react';
import "acss.scss";

render (<h2 className="fs24 lh32 c_primary fw700">{children}</h2>);
Copy the code
import react from 'react';
import { css, jsx } from '@emotion/core';
const primary = 'blue';

render(
<h2 className={css`
    font-size:24px;
    line-height:32px;
    color:The ${primary};
    font-weight:700; `} >That's the main heading</h2>
);
Copy the code

We even solved the problem of CSS-in-JS with native CSS. (I won’t expand on this point, but you can think about why csS-in-JS is emerging at a time when componentization is all the rage.) .

If you want to use the same experience in React-Native. Take a look at our ACSS component @SACSS/React-Native developed for React-Native.

import React from 'react';
import {Text, View, ImageBackground, Image} from './packages/withAcss';
import mImg1 from "./assets/1.jpg";
import mImg2 from "./assets/2.jpg";

export default function App() {
    return (
        <View bc="#f5f5f5" pt={100} ph={30} h="100%">
            <View mb={16} aic>
                <Image br={32} w={64} h={64} source={mImg1}/>
            </View>
            <Text c="#ffffff" p={16} bc="#4c5fe2" tac mb={16}>Hello world!</Text>
            <ImageBackground source={mImg2} mb={40}>
                <View bc="Rgba (255255255, 8)">
                    <Text fs={40} lh={100} tac fwb c="#4c5fe2">Hello Again!</Text>
                </View>
            </ImageBackground>
        </View>
    );
};
Copy the code

To achieve this effect with just a few lines of code, you can compare the amount of code below that used both styleSheets and Style-components. I know this is how delightfully wet.

The last

This article began as an explanation of the point at which CSS class names can be abbreviated. But in the end, I introduced my favorite ACSS and recommended three tools. After all, I spent a lot of effort, or HOPE to be seen and used by more people.

The point of view in this article is a summary of experience and goes with pragmatic logic, which may make the implementation look a bit ugly.

But what good is elegance if it can’t solve the problem? What omissions, but also ask everyone haihan, you can give me a message correction.

The solution

Update on 2021/02/21

SACSS: Static Atomic CSS

All this talk feels like theoretical talk. Here I years of experience, summed up an ACSS NPM library SACSS for everyone to use.

For ACSS, bootstrap, Material – UI, Github… There are all related libraries, and the most complete class library ** belongs to tailwindcss. Of course, they are all based on style-system theory. Getting started is relatively expensive and often requires the intervention of a designer.

Compared to these projects, the advantage of my solution is the simplicity and extreme CSS development experience. Simple to the whole logic only focus on naming rules, after reading the document 5 minutes will use, or even fully understand all the logic. The ultimate CSS development experience is when you get used to the rules and start to suspect that your fingers are slower than you think about CSS.

Of course, in order to pursue simple and development experience, this is also a disadvantage, is not perfect, not dealing with similar hover,focus… Equiintermediate state, also did not add any custom response points. This section is free to expand based on your own project and naming conventions.