Cascading Style Sheets (CSS) to provide developers with a declarative Style language is one of the must-have front-end skills. CSS is easy to learn based on comprehensive information and easy-to-understand syntax on the Internet, but it is widely scattered and difficult to master. In our daily development, limited by the original code chaos, DDL and other problems, often ignore the quality of CSS code, it is easy to write chaotic CSS files.

Code optimization Recommendations

  1. Simplify code with abbreviated attributes

Applicable to: Margin, padding, border, font, background, etc

This is not necessary in all cases, because when the value of a property is abbreviated, everything is always set, and sometimes we don’t want to set certain items in the value, so it’s up to the developer to decide.

  1. Merge selector

Using “, (comma) “to concatenate multiple selectors to define common properties not only reduces CSS file sizes, but also increases readability.

To make it easier to locate the problem, wrap a line after a comma.

  1. Name the class with a more semantic word

Name it with the goal that “the people who develop after you will not be confused.

  1. Order of property declaration

Reference: Bootstrap Property Order for Stylelint

If there are a large number of attributes in the selector, put the related attribute declarations together in the following order:

  1. Positioning: Positioning related, such as position, top/bottom/left/right, Z-index, etc
  2. Box Model: Box model related, such as display, float, margin, width/height, etc
  3. Typographic: Related to typesetting, such as font, color, line height, etc
  4. Visual: Visual correlation, such as background, color, etc
  5. Misc: Others, such as opacity, animation, etc

Personal advice: If the number of attributes is large, you can refer to these 5 categories for sorting and sorting. There is no need to be too tangled about the order.

.declaration-order { /* Positioning */ position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 100; /* Box-model */ display: block; float: right; width: 100px; height: 100px; /* Typography */ font: normal 13px "Helvetica Neue", sans-serif; The line - height: 1.5; color: #333; text-align: center; /* Visual */ background-color: #f5f5f5; border: 1px solid #e5e5e5; border-radius: 3px; /* Misc */ opacity: 1; }Copy the code
  1. References the parent selector with the ampersand symbol

& is a syntactic sugar provided in Sass and Less, used to indicate a reference to the parent selector. Antd Design source code is widely used advantages: very suitable for writing component styles, reducing the number of repeated words disadvantages: the cost of finding the corresponding style from the HTML class name increases

.header { .header-title {/* styles */} .header-title:after {/* styles */} .header-content {/* styles */} } /* Use & reference to optimize code πŸ‘‡ * /. The header {& - the title {/ * * / & styles: after {/ * styles * /}} & - content {/ * styles * /}}Copy the code

Use relevant technology

From The State of CSS 2020: technology survey, we can know The number of users and satisfaction rate of The current mainstream CSS tools (sample number of 10,000 +, for reference only), which is divided into four quadrants:

Evaluation: Low utilization rate, high satisfaction. Technology to watch. Adoption: High utilization rate, high satisfaction. Safety technology can be used. (Sass, BEM, PostCSS, Styled Components) Avoidance: Low usage and low satisfaction. Techniques best avoided for now. To be determined: High utilization rate, low satisfaction. If you are using these techniques, re-evaluate them.

CSS methodology

BEM: Modular naming specification

BEM (Block Block, Element, Modifier) is a normalized naming convention for class names.

There are only two hard problems in Computer Science: Cache Invalidation and Naming Things — Phil Karlton

What problem does πŸ™‹ BEM solve?

  • CSS has no scope and causes “style pollution” when it has the same class
  • When the CSS file is long, the structure is confusing due to different names
  • Non-standard naming makes it difficult for styles to locate the corresponding HTML elements, making it easy for different developers to write repetitive code

Advantages of BEM: modular, structured, reusable

πŸ™‹ BEM specification?

Any DOM Element can be a Block Element: a child of a Block that exists attached to the Block. Modifiers, such as an item in a list, the title of a card, or a selection in a selector, indicate the appearance, state, or behavior of a block or element. For example: Whether to click, whether to disable and other naming conventions:

.block__element–modifier

Block and Element with double underscore __ Link Element and modifier with double underscore — link block, Element, modifier with a single underscore — link element nested is not recommended. If nesting is required, it is time to extract a component from it

🌰 example

【 element-UI source 】github.com/ElemeFE/ele…

Atomic CSS: Atomized CSS

πŸ™‹ What is atomization?

Atom, “atom,” refers to the basic particle of chemical reaction is not separable

In ACSS, each non-detachable CSS class with a single CSS rule is called ACSS atom. HTML styles are composed of multiple CSS atoms written inline in THE HTML.

  • Advantages: No CSS files to maintain, inline “WHAT you see is what you get” in HTML; When an HTML element is moved/deleted, its style can be moved with it without additional update costs.
  • Disadvantages: Strong coupling of structure and style, not conducive to large project maintenance, prone to a lot of repetitive code.

🌰 example

<! <div class="D(f) Jc(c) Ac(c) ">Flex container </div> <! <div className="ant-col ant-col-xs-24 ant-col-sm-12 ant-col-md-8 ant-col-lg-6 gutter-row"></div>Copy the code

CSS pre/post processor

To provide CSS with more powerful functions (nesting, variables, operations, etc.) and make it easier to maintain, CSS preprocessors such as Sass, Less, and Stylus are born. Developers can develop with the easier syntax and features provided by these tools, and the preprocessor takes care of compiling the code into CSS for styling purposes.

Sass (Scss) & Less

Sass: grammar | Sass Chinese, language features | Less Chinese

πŸ™‹ Superiority of preprocessor?

  • Convert CSS from a declarative language to a programming language
  • Nested syntax increases the readability and maintainability of style files
  • The variable and blending features can reduce the number of duplicate style declarations

πŸ™‹ Sass. Vs. Less?

  • Less is more like CSS, easy to use, can be a smooth transition from CSS; The acceptability of Sass indentation syntax varies from person to person. Scss compatible with CSS is proposed in Sass3.0. Users can choose to use Sass or Scss.
  • Sass/Scss is more suitable when complex logic needs to be involved in the project CSS. Sass provides more powerful and programming-language-like syntax such as @function, @if/@else, and @while. When the style complexity of the project is not high, choose Sass or Less. (Here is a comparison example of Less and Scss syntax 🌰)
// Less

.mixin( @count )when( @count > 0 ){
    background-color: black;
}
.mixin( @count )when( @count <= 0 ){
    background-color: white;
}
.tag {
    .mixin(100);
}

// Scss
@function checkCount($count) {
    @if $count > 0 {
        return black;
    }
    @else {
        return white;
    }
}
.tag {
    background-color: checkCount(100);
}
Copy the code
  • Sass provides a command line syntax that allows you to parse Sass (compile Sass into CSS) from the command line when using Dart or Ruby, giving developers room to expand. Based on Sass’s good scalability, Sass frameworks such as Compass were born.

PostCSS

πŸ™‹ defined?

PostCSS in a narrow sense: “A tool for transforming CSS with JavaScript”, A tool for transforming CSS into JS code, provides the ability to parse CSS code into an AST and exposes JavaScript apis to developers that can modify CSS code.

PostCSS in general: A series of plug-ins based on the API provided by the PostCSS tool that can handle user-written CSS code. These plug-ins can also be called post-processors.

πŸ™‹ What are the popular PostCSS application scenarios?

  • Autoprefixer plug-in: Automatically adds browser prefix properties when packaging
Div {display: flex} // automatically converts to πŸ‘‡ div{display: -webkit-box; display : -webkit-flex; display : -moz-box; display : -ms-flexbox; display : flex; }Copy the code
  • Switching between dark/light modes through color value recognition and replacement Front-end sites support dark mode with one click
  • Stylelint plug-in: CSS code check tool
  • Postcss-utilities: Provides CSS shorthand for developers (atomized)
.cfx { @util clearfix; } // equivalent to πŸ‘‡. CFX :after {content: "; display: block; clear: both; } .rounded-top { @util border-top-radius(4px); } // Equivalent to πŸ‘‡. Rounded -top {border-top-left-radius: 4px; border-top-right-radius: 4px; }Copy the code

CSS in JS

styled-components /Emotion

  • High reusability: Encapsulates the CSS at the component level, adapting to the “component-based” front-end era, eliminating the need to maintain CSS files in the code.
  • High flexibility: Using styled components, it is easy to identify the style associated with a component; When an HTML element is moved/deleted, its style can also be moved/deleted.
  • Styled components will generate a unique class name for the style at compile time, and developers will no longer have to worry about class name duplication.
// Create a Title component that will render a styled <h1> tag const Title = styled. H1 'font-size: 1.5em; text-align: center; color: palevioletred; `; // Create a Wrapper component that will render a styled <section> tag and read the wrapperColor attribute as the background color background: ${props => props.wrapperColor || "palevioletred"}; `; // Use Title and Wrapper render(<Wrapper wrapperColor="red"> <Title> Hello World! </Title> </Wrapper> );Copy the code

πŸ™‹ Styled – Components Applicable scenarios

  • When developing with React or React Native
  • Small and medium-sized projects; Or large projects based on component libraries with less complexity in custom styles
  • Element styles on the page change little or nothing

conclusion

To sum up, CSS, as a basic skill, has many raw pain points. In recent years, developers around the world are constantly coming up with different optimization solutions. We should not forget to write CSS code when we pay attention to hot front-end topics such as React, NodeJS, and performance optimization

Reference

The Definitive GUIDE to CSS 4th Edition

NEC: A better CSS style solution

Code Guide by @AlloyTeam

Encoding specification by@mdo

The State of CSS 2020

BEM — Block Element Modifier

ACSS

Sass: grammar | Sass Chinese website

Language features | Less Chinese

hengg/styled-components-docs-zh

❀️ Thank you

That is all the content of this sharing. I hope it will help you

Don’t forget to share, like and bookmark your favorite things.

Welcome to the public account ELab team harvest dachang good article ~

We are from the front end department of Bytedance, responsible for the front end development of all bytedance education products.

We focus on product quality improvement, development efficiency, creativity and cutting-edge technology and other aspects of precipitation and dissemination of professional knowledge and cases, to contribute experience value to the industry. Including but not limited to performance monitoring, component library, multi-terminal technology, Serverless, visual construction, audio and video, artificial intelligence, product design and marketing, etc.