This article contains the following sub-sections. Since there are many contents involved, it is explained separately, and relevant links will be mentioned again in the corresponding sections
- Use of SASS around CSS 2020
- Styled – Components principle and usage guide for the CSS periphery, 2020
This article introduces the following solutions to problems encountered during CSS development, with examples and detailed explanations of each solution:
- preprocessor
- post-css
- css-in-js
- css-module
We then recommend a few style guides for writing CSS to better organize your code:
- BEM
- OOCSS
Finally, combining vUE – CLI and create-React-app, it analyzes its preset CSS scheme and recommends a better scheme that we can adopt in daily projects.
The text begins at 💗
As one of the three front-end sets, CSS will encounter some problems in actual development and use:
- The simple syntax of CSS is difficult to achieve code reuse and complex logic;
- Different browsers have different implementations of the new CSS features;
- Without modularity, the cascading nature of the global selector makes the style map difficult to maintain.
The solution
- For the first question, yes
preprocessor
,post-css
And so on the way to use another syntax to compile the way to solve the native CSS, can also be usedcss-in-js
Control the generation of styles directly with JS. - For compatibility with the latest features, we can use
post-css
orcss-in-js
Automatically prefix the browser or add polyfill to the style. - Adding modularity to CSS is essentially adding unique tags to the selectors of different modules that can be used
css-module
orcss-in-js
Automatically add unique class names to various elements.
The solution
preprocessor
CSS preprocessors are new languages that extend the CSS. They add variables, nesting, mixins, and functions to the original CSS, and generate CSS through compilation. Certain preprocessors, such as SASS, are to CSS what TS is to JS (learn more about TS again in new ways). Common CSS preprocessors include
- Sass website
- Less website
- The stylus’s official website
The function of the three preprocessors is very repetitive, and the difference between the relevant syntax (please refer to CSS preprocessors again for specific differences) is essentially the same. If you learn one of the preprocessors, you can switch painlessly to other preprocessors.
Refer to this article for information about sASS useUse of SASS around CSS 2020
postcss
Postcss is often classified as a preprocessor, but not here. The essential difference between it and the preprocessor is that it does not import third-party files. The input CSS file is still the output CSS file. It is to CSS what Babel is to JS.
More precisely, postCSS is like @babel/core in Babel, which takes a CSS file and turns it into an abstract syntax tree, where plug-ins can be introduced to do whatever you want (such as validate the syntax or add browser-specific prefixes), and then generate new CSS from the modified abstract syntax tree. Postcss without plug-ins can be represented as
const postcss = code => code
Copy the code
The plug-in
To realize the value of PostCSS, you can choose the plug-in from the plug-in list. You can also customize the plug-in based on the PROVIDED API to implement your own customized functions. For more details, see Developing postCSS Plug-ins. Here are some of the more common ones.
- Even if you haven’t heard of postcss, Autoprefixer is a plugin for adding prefixes recommended by different browsers to related properties. Such as
Placeholder {color: gray; }Copy the code
// placeholder {color: green; } :-ms-input-placeholder { color: gray; } ::placeholder { color: gray; }Copy the code
- Cssnext and postCSS-preset -env can preset a new version of CSS to an old version of CSS that is not implemented by the browser. Yes, the plugin is used to convert the new syntax and provide polyfills. Of the two plug-ins, the latter replaces the former, the former is obsolete.
- Precss can implement the functions of preprocessors like SASS (syntax is similar to SASS) and relies on postCSS-PREset-ENV, so it can replace preprocessors to some extent.
To learn more about PostCSS, see PostCSS Deep Dive
css-in-js
Speaking of CSS-in-JS, some people may think of HTML-in-JS, the front end of the three major pieces at the moment under JS, namely all-in-JS.
JSX is a syntactic extension of ECMAScript that requires a compilation process to become a standard ECMAScript syntax, and then generates the DOM.
Although CSS-IN-JS also realizes the function of writing other languages in JS, its idea is just a layer of packaging. On the basis of JSX (for example, styled- Component uses the React.createElement method), the received element or component is further added with regular attributes and a unique className, and the corresponding stylesheet is generated to achieve modularity and other effects.
Css-in-js solutions also have several wheels that can be used out of the box, for example
- styled-components
- styled-jsx
- emotion
As with the preprocessor, it is described in detail here as styled- Components, and the other implementations are similar.
Refer to this article for further explanation of styled- ComponentsStyled – Components principle and usage guide for the CSS periphery, 2020
Like JSX, CSS-in-JS is primarily used with React.
css-module
background
Css-in-js puts part or all of the style code into JS, which not only realizes the reuse of code, but also causes the strong coupling between CSS and JS. What is a better way to achieve CSS modularization?
Js is how to solve the modularity problem, one of the ideas is to use the namespace (refer to the usage of namespace in TS), that is, a series of namespace internal attributes mounted to the same global variable, so that the project is easy to maintain and reduce the probability of naming conflicts. From various third-party implementations (such as AMD), JS now has a language-level modularity :esModule.
The modularity of CSS is to solve the problem of selector conflict in the global scope. Until a third party implements it, we can guarantee the uniqueness of selector reference through a series of naming conventions (such as BEM) introduced later, but with the increase of development cost caused by strict compliance with the specification. Until The CSS community had its own modularity specification :CSS Modules (see The End of Global CSS for background on CSS Modules).
Basic usage
Write normal CSS styles
/* style.css */
.className {
color: green;
}
Copy the code
Then import it from JS
import styles from "./style.css";
// import { className } from "./style.css";
element.innerHTML = '<div class="' + styles.className + '">';
Copy the code
It is also possible to reuse other style declarations using comPoses or toggle scopes using :global and :local. Refer to the official documentation and Interoperable CSS for details.
The principle of
CSS files processed by the CSS Module are compiled into a standard low-level interchangeable format file :ICSS for example
:export {
className: _className_97fd867fsfg;
}
._className_97fd867fsfg {
color: green;
}
Copy the code
This file is imported by other CSsmodule or JS files, where the local className is mapped to the global _className_97fd867fsfg, modularized. In addition, import and other implementations are similar, so I won’t repeat them here.
implementation
CSS – Loader of Webpack and CSS – Modulesify of Browserify are implemented, and relevant features can be realized through relevant configuration.
methodology
The CSS methodology refers to a set of recommended guidelines for organizing code to improve development efficiency, such as
BEM
BEM is a class naming convention where BEM stands for Blocks, Elements, and Modifiers and class names are named block–modifier-value
- A block represents a separate entity, which can be understood as a module, such as Header, Container, Menu, checkbox, and input
- Elements are parts of a block, such as menu Item, list item, Checkbox Caption, header title
- Modifier refers to a display or action of block or Elements, such as disabled, highlighted, checked, fixed, size big, color yellow
OOCSS
OOCSS stands for Object Oriented CSS. A CSS Object is a reusable visual pattern that can be abstracted into a single block of code (HTML elements of a specific structure and corresponding class names) that is reused throughout the site. For example, an image has descriptions next to it that contain fixed (or optional) structures.
< div class = "media" > / / media is the most outer layer object class < a href = "http://twitter.com/stubbornella" class = "img" > < img src="http://a3.twimg.com/profile_images/72157651/tattoo_pink_bkg_square_mini.jpg" alt="Stubbornella" /> </a> <div class="bd"> <a href="http://twitter.com/stubbornella">@Stubbornella</a> <span class="detail">14 miniutes ago</span> </div> </div>Copy the code
Two design principles
- Separate structure and skin Separate structure and skin will define repetitive vision as skin, and the structure should be represented by a general class name instead of a specific type of element, such as IMG, to facilitate the replacement of corresponding parts of the structure.
- Separate container and content Separate container and content, i.e., a part of the content is the same wherever it is located
.myObject>h2
Set the style, otherwise h2 will look different in other locations.
other
Other common ones are SMACSSMACSS, SUITCSS, and Atomic.
conclusion
As mentioned in the CSS Module section, these rules can increase development costs and serve as a facilitator when there are many better solutions.
Best practices
So now we come to the last part, we’ve seen so many theories, how do we use them in the project?
Before we answer that question, let’s take a look at what the two best projects did.
vue-cli
Vue-cli is the official scaffolding of VUE
- Use CSS Modules to solve module problems
- PostCSS is used, autoprefixer is enabled by default, and CSS properties browser-specific prefixes are added
- You can choose any of the Sass, Less, or Stylus preprocessors when initializing your project
create-react-app
Create-react -app is the official react scaffolding
- Use CSS Modules to solve module problems
- React does not recommend reusing classes across components because it makes preprocessors less useful
- Use PostCSS Normalize to reset the default browser styles to avoid cross-browser differences
- PostCSS is used, autoprefixer is enabled by default, and CSS properties browser-specific prefixes are added
conclusion
Here are some general recommendations
- Use CSS Modules to solve modularity problems
- Compatibility problems use PostCSS
- Code reuse and complex logic choose a preferred preprocessor, such as SASS
The specific choice can be based on their own situation, and can add appropriate conventions.
This should not be a problem once we have a global understanding of CSS related scenarios, right? 🙀