Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to avoid common css errors

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this article, the editor introduces in detail "how to avoid common css errors". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to avoid common css errors" can help you solve your doubts.

As we know today, the CSS language is an important part of web. It gives us the ability to draw the way elements are displayed on a screen, web page, or other media.

It is simple, powerful, and declarative. We can easily implement complex things, such as Dark / Light mode. However, there are many misunderstandings and misuses about it. These turn CSS tags into complex, unreadable and non-extensible code.

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

1. No pre-design

It is possible to finish the task more quickly without thinking about it, which also gives us a sense of speed and achievement. However, in the long run, this will have the opposite effect.

You must think carefully before you write the code. What approach will we take to design components? Do we want to build our components in an atomic way? Are we willing to create a practical system that can be combined? Do we want an already built-in UI library? Do we want our CSS to be global scoped or component scoped?

Having a clear goal will help us choose the best tool. This will save us from redundancy and violation of DRY. There are many effective ways to design an application. The most common ineffective is improvisation.

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

Look at an example:

/ * ❌ adds discrete values everywhere * / .card {color: # edb361; background-color: # 274530; padding: 1remt;} / * ✅ defines topic-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);}

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

2. The Chinese translation of CSS Code SmellsCode Smell is generally referred to as "code smell", or "code smell". It is a hint that there is an error somewhere in the code, and developers can use this smell to track down the problem in the code.

Code smells is not bug. They will not hinder the normal operation of the system. They are just bad practices that make our code more difficult to read and maintain.

Here, list some of the most common ones and how to overcome them:

:: symbol

It is common to use the:: symbol in pseudo elements and pseudo classes. This is part of the old CSS specification, and browsers continue to support it as a fallback. However, we should use::, for example:: before,:: after,:: frist-line..., in pseudo-classes:, for example: link,: visited,: first-child...

Use strings to concatenate classes

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

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

There seems to be no problem until the developer tries to search the code base for the .card-selected class. It will be difficult for developers to find this class.

Incorrect use of abbreviations

The abbreviation of CSS is very good, which allows us to prevent the code from being too verbose. But sometimes we don't use them deliberately. In most cases, the abbreviation background is used accidentally.

/ * ❌ since we are only setting a property, we do not need to use abbreviations. * / .foo {background: # 274530;} / * ✅ uses the correct CSS attribute * / .foo {background-color: # 274530;}

! misuse of important

! important rules are used to override specific rules. Its use focuses on overriding a style that cannot be overridden in any other way.

It is often used in more specific scenarios where the selector can complete the task.

This text is in the inner div.

.inner {color: blue;} / * ❌ overrides color * / .inner {color: orange! important;} .inner {color: blue;} / * inner uses a more specific selector rule that takes precedence over more general rules. * / .inner p {color: orange;}

Force the use of attribute values

It is common for a magic number to appear in the CSS code base. They bring quite a lot of confusion. Sometimes, we may find long numbers in the code because the developer is trying to overwrite an attribute that he is not sure about.

/ * ❌ Brute forces this element to be at the front of the z axis * / .modal-confirm-dialog {z-index: 9999999;} / * ✅ plans ahead and defines all possible use cases * / .modal-confirm-dialog {z-index: var (--z-index-modal-type);} 3. Do not scope CSS class names

Due to the nature of the CSS language, it is easy to see elements inadvertently stereotyped by a bad class name. This problem is very frequent, so there are quite a number of solutions to solve it.

In my opinion, the best two are:

Use naming conventions

CSS Modules

Naming convention

The most popular naming method is BEM 101. It represents the Block, Element, Modifier methods.

[block] _ [element]-- [modifier] / * Example * / .menu__link--blue {...}

The goal is to create unique names by letting developers understand the relationship between HTML and CSS.

CSS Modules

My biggest concern about the BEM approach is that it is time-consuming and depends on developers to implement it. 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

Pixels are used quite frequently because they seem easy and intuitive to use at first. The opposite is true. For a long time, pixels are no longer hardware-based. They are only based on an optical reference unit.

Px is an absolute unit. What does that mean? That is, we can't scale properly to satisfy more people.

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

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

In general, the most commonly used replacement units for px are rem and em. They represent the relative size of fonts in a relative way from box to text.

Rem represents the size relative to the root font-size.

Em represents the size relative to the size of the element.

By using rem, we will be able to express the layout according to the font size preferred by the user.

In the screenshot above, we can see how the layout based on rem units can be extended and adapted to different default font sizes.

5. Ignore browser support

When starting to develop a website, it is important to define our target customers. It is common to skip this step and code directly.

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

As long as we can provide appropriate backup solutions, we can still be committed to accepting late-stage features like subgrid. It's always a good idea to define a progressive functional experience. As a feature gets more support, we can gradually abandon its backup plan.

Tools like caniuse.com or browserslist.dev are very helpful in this regard. The native autoprefixer capabilities of tools like postcss will help our CSS gain wider support.

Read here, this article "how to avoid common css errors" article has been introduced, want to master the knowledge of this article still need to practice and use to understand, if you want to know more about the article, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report