Jose Granja translator: Medium

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom. In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.

The CSS language is an important part of the Web as we know it today. It gives us the ability to draw how elements appear on screens, web pages, or other media.

It’s simple, powerful, and declarative. We can easily implement complex things like dark/light mode. However, there are many misunderstandings and misuses of it. These can turn CSS tags into complex, unreadable and unextensible code.

How can we prevent this from happening? Avoid the most common mistakes by following best practices. In this article, we will summarize the 5 most common mistakes and how to avoid them.

1. No pre-design

Doing it right away, without thinking, may get things done faster, which gives us a sense of speed and accomplishment. But, in the long run, it can have the opposite effect.

Before you write code, you have to think about it. What approach will we take to design components? Do we want to build our components atomically? Are we willing to create a composable utility system? Do we want a BUILT-IN UI library? Do we want our CSS to be globally scoped or component-scoped?

Having a clear goal will help us choose the best tool. This will save us from redundancy and DRY violations. There are many effective ways to design an application. The most common thing that doesn’t work is improvisation.

Our code must be predictable and easy to extend and maintain.

Here’s an example:

/* ❌ add discrete values */. Card {color: #edb361; background-color: #274530; padding: 1rem; } /* ✅ define theme-based attributes */ :root {--primary-bg-color: #274530; --accent-text-color: #edb361; - spacing - unit: 0.5; } .card { color: var(--accent-text-color); background-color: var(--primary-bg-color); padding: calc(var(--spacing-unit) * 2rem); }Copy the code

In the example above, we can see that everything becomes readable and clear when using CSS variables for theme design. The first.card definition looks completely random, and this component is not easily extended.

2. CSS Code Smells

Code Smell, commonly known in Chinese as “Code Smell” or “Code Smell,” is a signal that something is wrong somewhere in the Code, and developers can use it to hunt down problems in the Code.

Code smells is not a bug. They do not interfere with the normal operation of the system. They’re just bad practices that make our code harder to read and maintain.

Here are some of the most common and how to overcome them:

Symbol: :

It is common to use the :: notation in pseudo-elements and pseudo-classes. This is part of the older CSS specification, and browsers continue to support it as a fallback. However, we should use :: in pseudo-elements, such as ::before, ::after, ::frist line… , use: in pseudo-classes, e.g. : Link, :visited, :first-child…

Concatenate classes using strings

It is very popular to use the Sass preprocessor to help with our CSS code base. Sometimes when we try DRY, we create classes through the concatenation & operator.

.card {border: 0.5 solid rem # FFF; /* ❌ failed attempt to be dry */ &-selected {border-color: #000; }}Copy the code

There seems to be no problem until the developer tries to search the.card-selected class in the code base. Developers will have a hard time finding this class.

Incorrect use of abbreviations

The CSS shorthand is great, and it keeps the code from being too verbose. But sometimes we don’t use them deliberately. In most cases, the background abbreviation is used by accident.

/* ❌ Since we are only setting a property, there is no need to use shorthand. */ .foo { background: #274530; } /* ✅ use the correct CSS attributes */. Foo {background-color: #274530; }Copy the code

! Incorrect use of important

! The important rule is used to override specific rules. Its use is primarily focused on overwriting a style that cannot be overridden in any other way.

It is typically used in scenarios where more specific selectors can do the job.

<div class="inner"> <p>This text is in the inner div.</p> </div> <style> .inner { color: blue; } /* ❌ rewrite color */. Inner {color: orange! important; } </style> <style> .inner { color: blue; } /* ✅ uses a more specific selector rule that takes precedence over the more general rule. */ .inner p { color: orange; } </style>Copy the code

Enforce the use of attribute values

It’s not uncommon for a magic number to appear in a CSS code base. They bring a fair amount of chaos. Sometimes, we might find long numbers in code because the developer is trying to override an attribute he is not sure about.

/* ❌ Brute forces the element to be at the front of the z-axis */. Modal-confirm-dialog {z-index: 9999999; } /* ✅ Plan ahead and define all possible use cases */.modal-confirm-dialog {z-index: var(--z-index-modal-type); }Copy the code

3. Do not scope CSS class names

Because of the nature of the CSS language, it’s easy to inadvertently stereotype an element with a bad class name. This problem is very frequent, so there are quite a few solutions to solve this problem.

In my opinion, the best two are:

  • Using naming conventions
  • CSS Modules

Naming conventions

The most popular naming method is BEM 101. It stands for Block, Element, Modifier methods.

[block]__[element]--[modifier]
/* Example */
.menu__link--blue {
  ...
}
Copy the code

The goal is to create unique names by giving developers an understanding of the relationship between HTML and CSS.

CSS Modules

My biggest concern with the BEM approach is that it is time consuming and developer dependent. The CSS module occurs on the preprocessor side, which makes it error-free. It generates a random prefix/name for our CSS module class name.

4. Use px units

Pixel is used quite frequently because it seems easy and intuitive to use at first. The opposite is true. Pixels are not hardware-based for a long time. They’re just based on an optical reference unit.

Px is an absolute unit. What does that mean? It’s that we can’t scale properly to satisfy more people.

What should we use instead? The relative units are the way to go. We can rely on these to better express our dynamic layout. For example, we can use ch to express the width of a div based on the number of characters.

.article-column {/* ✅ Our element will hold up to 20 inherited font size characters. */ max-width: 20ch; }Copy the code

In general, the most common substitutions for PX are REM and EM. They represent the relative size of a font in a relative way from box to text.

  • remRepresents relative to the rootfont-sizeThe size of the.
  • emRepresents the size relative to the element size.

By using REM, we will be able to express the layout according to the user’s preferred font size.

In the screenshot above, we can see how the REM cell-based layout can scale and accommodate different default font sizes.

5. Ignore browser support

When starting to develop a website, it is crucial to define our target audience. It’s common to skip this step and go straight to coding.

Why is it important? It helps us understand which device our application will be used on. After that, we can define which browsers and versions we will support.

As long as we can provide a proper fallback, we can still commit to accepting late stage features like subGrid. It’s always a good idea to define a progressive feature experience. As a feature gets more support, we can move away from its fallback.

Tools like caniuse.com or Browserslist.dev can be helpful in this regard. The autoprefixer functionality that comes with tools like Postcss will help our CSS become more widely supported.

conclusion

We’ve seen how to improve our CSS code. Following a few simple guidelines, we can implement a declarative, reusable, and readable code base. We should put as much effort into CSS as we do into Javascript.

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: levelup.gitconnected.com/top-5-css-m…

Have a dream, have dry goods, wechat search [big Move the world] pay attention to this in the early morning is still in the bowl washing wisdom.

In this paper, making github.com/qq449245884… Has been included, a line of large factory interview complete test sites, information and my series of articles.