At the end of last year, I took a moment to summarize the modularity of CSS.

  • CSS development
  • CSS Modular Definition
  • Modular implementation of the CSS

Original address, welcome to Star and subscribe to my blog.

CSS development

When we write CSS, we actually go through the following stages:

  • Handwritten source CSS
  • Use the preprocessor Sass/Less
  • Use postprocessor PostCSS
  • Using CSS modules
  • Use CSS in JS

Handwritten source CSS

When we first learned how to write pages, we all learned how to write CSS, which is the following cases:

  • Inline style, which means writing CSS code directly in the STYLE property of the HTML.
  • Inline styles, in which a class is written inside the style tag in HTML H, are provided for use on the current page.
  • Import styles, that is, import other styles in inline styles using the @import method to make them available to the current page.
  • External styles, which use the LINK tag in HTML, load styles and provide them to the current page.

In the process of constant exploration, we gradually formed the main writing habits of writing inline styles and external styles.

I’m sure you’re wondering at this point, why not use inline styles?

Disadvantages of using inline styles

  • Styles cannot be reused.
  • The style weight is too high and the style is not covered well.
  • There is no separation between the presentation layer and the structure layer.
  • Cache cannot be implemented, affecting loading efficiency.

Then we go further, why not use imported styles?

Using @import in CSS has been tested in two ways:

In IE6-8, the stylesheet pointed to by the @import declaration is not loaded concurrently with other resources on the page, but is not downloaded until all resources on the page are loaded.

2. If you remove @import CSS from the link tag, the page will wait until all resources are loaded before parsing the @import CSS from the link tag.

Disadvantages of using imported styles

  • Import styles that can only be placed on the first line of the style tag.
  • The @import declared stylesheet does not take full advantage of the browser’s concurrent resource requests, and its loading behavior tends to be delayed or suspended by other resource loads.
  • Page style flickering may occur due to the delayed loading of the @import stylesheet.

Use the preprocessor Sass/Less

Over time, we’ve come to realize that writing native CSS is not friendly. For example, native CSS does not support variables, does not support nesting, does not support parent selectors, and so on. These issues have led to preprocessors like SASS/Less.

The preprocessor mainly enhances the SYNTAX of CSS to compensate for these problems, but in essence, the packaged result is the same as raw CSS, only more developer-friendly and smoother to write.

Postprocessor PostCSS

With the continuous development of front-end engineering, more and more tools were developed by the front-end gurus, the vision was to leave all the repetitive work to the machine to do, in the CSS field came PostCSS.

Postcss can be called as the Babel of CSS. Its implementation principle is to analyze our CSS code through AST, and then process the results of analysis, thus derivating many kinds of CSS use scenarios.

The postCSS is used in the following scenarios:

  • Check CSS syntax with the Stylelint
  • Automatically added the browser prefix autoprefixer
  • Compile the syntax for CSS Next

More usage scenarios of PostCSS

CSS modularity is growing rapidly

As modularity-based frameworks like React and Vue become more widely available, we’ll have fewer opportunities to write native CSS. We often break the page up into many small pieces, and then build those pieces into the final page like building blocks.

But we know that CSS matches elements by class name. If two components use the same class name, the latter will overwrite the former style.

To solve this problem, the concept of CSS modularity was developed.

CSS Modular Definition

  • Are you having trouble naming a class?
  • Are you worried about using the same class name as someone else?
  • Are you frustrated by the lack of hierarchy?
  • Are you frustrated that your code is hard to reuse?
  • Are you intimidated by the sheer size of common.css?

If you encounter these problems, then it is necessary to use CSS modularity.

Modular implementation of the CSS

BEM naming convention

BEM means block, element, or modifier. Is a front-end naming methodology proposed by the Yandex team. This clever naming makes your CSS classes more transparent and meaningful to other developers.

The naming convention for BEM is as follows:

/* Blocks are commonly referred to as components or modules in Web application development. Each block is logically and functionally independent of the other. * /
.block{}/* The element is a component of a block. The element cannot be used outside the block. BEM does not recommend nesting other elements within an element. * /
.block__element{}The /* modifier is used to define the appearance and behavior of a block or element. The same block with different modifiers can look different */
.block--modifier{}Copy the code

By beM naming way, can let our CSS code hierarchy is clear, through strict naming can also solve the problem of naming conflicts, but also can not completely avoid, after all, it is only a naming constraint, not according to the specification can still run.

CSS Modules

CSS Modules means that we import our CSS code like import JS. Each class name in the code is an attribute of the imported object. In this way, we can specify the REFERENCED CSS style when we use it.

And CSS Modules will automatically convert class names to hash values when packaging, completely eliminating CSS class name conflicts.

The usage is as follows:

1. Define the CSS file.

.className {
  color: green;
}
/* Write global styles */
:global(.className) {
  color: red;
}

/* Style reuse */
.otherClassName {
  composes: className;
  color: yellow;
}

.otherClassName {
  composes: className from "./style.css";
}
Copy the code

2. Import the CSS file in the JS module.

import styles from "./style.css";

element.innerHTML = '<div class="' + styles.className + '" >';
Copy the code

3. Configure CSS-Loader packaging.

CSS Modules cannot be used directly, but need to be packaged. You can configure CSS Modules by configuring the Modules attribute in CSS-Loader.

// webpack.config.js
module.exports = {
  module: {
    rules: [{test: /\.css$/.use: {loader: 'css-loader'.options: {
            modules: {
              // Customize the hash name
              localIdentName: '[path][name]__[local]--[hash:base64:5]',}}}]}};Copy the code

4. The final packaged CSS class name is generated from a long string of hash values.

._2DHwuiHWMnKTOYG45T0x34 {
  color: red;
}

._10B-buq6_BEOTOl9urIjf8 {
  background-color: blue;
}
Copy the code

CSS In JS

CSS in JS means to use THE JS language to write CSS, without the need for some separate CSS files, all THE CSS code is placed inside the component, in order to achieve the modular CSS.

In fact, CSS in JS is a writing idea, and there have been more than 40 implementations of schemes, the most famous being styled components.

The usage is as follows:

import React from "react";
import styled from "styled-components";

// Create a styled H1 tag
const Title = styled.h1` the font - size: 1.5 em. text-align: center; color: palevioletred; `;

// Create a styled section tag
const Wrapper = styled.section` padding: 4em; background: papayawhip; `;

// Define styles dynamically through attributes
const Button = styled.button`
  background: ${props => (props.primary ? "palevioletred" : "white")};
  color: ${props => (props.primary ? "white" : "palevioletred")}; font-size: 1em; margin: 1em; Padding: 0.25 em 1 em; border: 2px solid palevioletred; border-radius: 3px; `;

// style reuse
const TomatoButton = styled(Button)` color: tomato; border-color: tomato; `;

<Wrapper>
  <Title>Hello World, this is my first styled component!</Title>
  <Button primary>Primary</Button>
</Wrapper>;
Copy the code

As you can see, we wrote the CSS directly in JS. In this case, we created the styles when we defined the source HTML, and we rendered the styled components when we used them.

In addition, there are other well-known libraries:

  • emotion
  • radium
  • glamorous

conclusion

Put a summary diagram at the end.

Refer to the link

  • bem
  • css modules
  • css in js
  • On the MODULarization of CSS
  • vs @import