• Author: Chen Da Yu Tou
  • Making: KRISACHAN

preface

I recently heard that TypeScript3.7 added support for Optional Chaining. I was thinking about upgrading the TS version of ying-Template, the fish-head scaffolding, and found this message on the command line:

‘postCSS-cssNext’ has been replaced by ‘postCSs-preset -env’. IO /blog/deprec…

Postcss-cssnext has been changed to PostCSS-preset -env, but this article comes out after seeing this sentence, out of curiosity, I went to the official website of PostCSS, and then thought about the development of CSS in these years.

Brief introduction to modern CSS

From the release of CSS1.0 in 1997, CSS has gone through 22 years from simple text typesetting to cool 3D animation now. The development of CSS is shown in the figure below:

[Photo by MDN]

With the development of the Internet, people’s requirements for web pages have changed from just showing pictures and texts to all kinds of interaction and visual effects requiring more experience. CSS is constantly updated for this purpose.

With the increasing complexity and diversification of Web business, front-end development has also changed from simple Web page to Web App, where the concept of “front-end engineering” was born. A complete Web app is often very large and complex, and even many people will jointly maintain it. Writing jQuery is no longer enough to support modern needs. The same is true of CSS. It is no longer enough to write a few margins, padding or HTML in one go, and due to the increase in staffing, different development, naming conventions, and whether styles will conflict must also be considered.

In addition to engineering issues, there is also the relationship between CSS and browsers that we have to consider. Although CSS is evolving rapidly, browsers are slow to support new CSS features. So while certain attributes have been available for years, they are often not widely used because of browsers.

Although in the actual development process, CSS has such problems that people can not be ignored, but “methods always more than difficult”, there are many enthusiastic leaders in the front-end world trying to solve these problems. Let fish head share some CSS related tips and tricks with you.

The first CSS modularity – CSS naming rules

Named has been developers headaches, in front, in addition to JS naming variables, and the element class named, although we are free to name, like can even use. A. b. c and other pointless rules to name, but if it is a long-term, large or collaboration so named in the project, I’m afraid I’m a sucker for a punch. This time, we’re going to share some of the industry’s common naming conventions for avoiding beatings.

OOCSS(Object-Oriented CSS)

OOCSS has two coding principles:

  • Structure is separated from style
  • Containers are separated from content

Let’s look at an example from the official website:

<div class="mod grab"> 
    <b class="top">
        <b class="tl"></b>
        <b class="tr"></b>
    </b> 
    <div class="inner">
        <div class="hd">
            <h3>grab</h3>
        </div>
        <div class="bd">
            <p>Body</p>
        </div>
    </div>
    <b class="bottom">
        <b class="bl"></b>
        <b class="br"></b>
    </b> 
</div>
Copy the code

In this case, mod is the parent class from which all classes are derived, and.grab is the subclass.

As for.top,.inner and bottom, as the name implies, they are subboxes in different positions.

This is named after the container.

BEM

BEM is a set of words for Block, Element, and Modifier.

In the selector, we use the following three symbols to represent the above

  • – Hyphen: used only as a hyphen to connect multiple words of a block or child element.
  • __Double underline: Double underline is used to connect a block to its children
  • _Single underscore: A single underscore is used to describe a state of a block or its children

It looks like this: type-block__element_modifier

Here’s an example from the official website:

<style>
    .button {
        display: inline-block;
        border-radius: 3px;
        padding: 7px 12px;
        border: 1px solid #D5D5D5;
        background-image: linear-gradient(#EEE.#DDD);
        font: 700 13px/18px Helvetica, arial;
    }
    .button--state-success {
        color: #FFF;
        background: #569E3D linear-gradient(#79D858.#569E3D) repeat-x;
        border-color: #4A993E;
    }
    .button--state-danger {
        color: # 900;
    }
</style>
<button class="button">
	Normal button
</button>
<button class="button button--state-success">
	Success button
</button>
<button class="button button--state-danger">
	Danger button
</button>
Copy the code

SMACSS

SMACSS, a rule that looks much like OOCSS.

There are only the following six cores:

  • Base: The basic style naming convention for the page
  • Layout: Layout naming rules
  • Module: naming rule of a Module
  • State: State naming rule
  • Theme: Theme naming rule
  • Changing State: naming rules for mutable states

The modifier is –, and the submodule is __

Here’s an example from the official website:

<style># header {... # primarynav} {... # maincontent} {... }</style>
<div id="header"></div>
<div id="primarynav"></div>
<div id="maincontent"></div>
Copy the code

Enabling CSS – preprocessor

CSS preprocessor is a program that allows you to generate CSS using the preprocessor’s own unique syntax. There are many CSS preprocessors to choose from, and most CSS preprocessors add some features that native CSS does not have, such as code mixing, nested selectors, inheritance selectors, etc. These features make CSS structures more readable and maintainable.

sass

Sass is the oldest, most mature, stable and powerful professional CSS extension language in the world! (O_o??)

Sass can use variables, nested rules, mixers, inheritance, and other concepts that are unique to programming languages. Examples of code are as follows:

$nav-color: #F90;
nav {
  $width: 100px;
  width: $width;
  color: $nav-color;
}

/ / the compiled

nav {
  width: 100px;
  color: #F90;
}
Copy the code

less

Less is a CSS preprocessing language, which extends the CSS language, adding variables, mixins, functions and other features, making the CSS easier to maintain and expand.

Example code is as follows:

@base: #f938ab;

.box-shadow(@style.@c) when (iscolor(@c)) {
  -webkit-box-shadow: @style @c;
  box-shadow:         @style @c;
}
.box-shadow(@style.@alpha: 50%) when (isnumber(@alpha)) {
  .box-shadow(@style, rgba(0.0.0.@alpha));
}
.box {
  color: saturate(@base.5%);
  border-color: lighten(@base.30%);
  div { .box-shadow(0 0 5px.30%)}}/ / the compiled
.box {
  color: #fe33ac;
  border-color: #fdcdea;
}
.box div {
  -webkit-box-shadow: 0 0 5px rgba(0.0.0.0.3);
  box-shadow: 0 0 5px rgba(0.0.0.0.3);
}
Copy the code

stylus

Stylus, expressive, dynamic, robust CSS

Example code is as follows:

body
  font 12px Helvetica, Arial, sans-serif

a.button
  border-radius 5px
Copy the code

You don’t need {} :; Preprocessors, I personally don’t like this, but for many developers who like simplicity, it’s a great way to write

Sorcerer – CSS Houdini

A little time to see the CSS out new properties, but because the browser compatibility issues, so often can see but can’t use, even though some attributes can be used, but also because of the reality of each browser and unexpected bugs, so that means we have to wait until after a property out after 5 years or more to use? It’s been 9,012 years, huh?

Of course not. Next we can learn about the sorcerer’s existence CSS Houdini

What is CSS Houdini?

CSS Houdini is a set of low-level apis that expose parts of the CSS engine so that developers can extend CSS through this set of apis. It gives developers direct access to CSSOM and allows them to write browser-parsed CSS code through this set of apis, which allows developers to implement their desired CSS functionality without having to wait for the browser to implement it.

/ pictures from: www.qed42.com/blog/buildi…

As shown above, the different apis correspond to different browser rendering sessions, which are explained by the popular concept of hook functions with different life cycles of browser loading.

CSS Houdini is JS IN CSS, niubility..

How does CSS Houdini work?

The seven apis we have access to are as follows:

  1. Typed OM API
  2. Properties & Values API
  3. Paint API
  4. Layout API
  5. Animation worklet
  6. Parser API
  7. Font Metrics API

Mmmm, although there are seven apis (and a few more on Houdini Drafts), browser support actually works like this:

[Photo: ishoudinireadyyet.com/]

CSS Houdini works as follows:

/ pictures from: www.qed42.com/blog/buildi…

  1. The hook enters the render process
  2. JS is the core of this hook
  3. Using JS Typed OM, you can mount custom properties, draw graphics, layouts as well as animations
  4. There are two other apis: the Parser API and the Font Metrics API. They are used to register new csS-related things

Some examples are

This article is not going to cover CSS Houdini in detail, so I won’t draw all the demos, but if you’re interested, check out “Sources” at the bottom for more detailed information.

Typed OM

<style>
    * {
        margin: 0;
        padding: 0;
    }
    .box {
        background: linear-gradient(to right, #2c3e50.#4ca1af);
    }
</style>
<div class="box" id="box"></div>
<script>
    'use strict'
    box.attributeStyleMap.set('width', CSS.px(200))
    box.attributeStyleMap.set('height', CSS.px(200))
    const [x, y] = 'width,height'
    .split(', ')
    .map(val= > Number.parseInt(box.computedStyleMap().get(val)))
    box.attributeStyleMap.set('transform'.new CSSTranslate(CSS.px(x), CSS.px(y)))
    console.log(box.computedStyleMap().get('transform'))
    console.log(window.getComputedStyle(box, null) ['transform'])
</script>
Copy the code

Typed OM: Typed OM: Typed OM: Typed OM: Typed OM: Typed OM: Typed OM: Typed OM: Typed OM However, Typed OM JS API computedStyleMap is used to get the result is a set of specific attributes, which is very conducive to our secondary operations.

Paint API

The Paint API allows you to write CSS styles using properties such as Canvas. It is also easy to use. Look at the slides

First we’ll create a new file called registerpaint.js and write the following code inside:

registerPaint('circle-ripple'.class {
  static get inputProperties() { return [ '--circle-color'.'--circle-radius'.'--circle-x'.'--circle-y'
  ]}
  paint(ctx, geom, props, args) {
    const x = props.get('--circle-x').value;
    const y = props.get('--circle-y').value;
    const radius = props.get('--circle-radius').value; }}Copy the code

Then create a new index, HTML, and registered in JS code above written registerPaint. JS, as follows: CSS. PaintWorklet. AddModule (‘ registerPaint. JS);

The specific code is as follows:

<style>
    .el {
          --circle-radius: 0;
          --circle-color: deepskyblue;
          background-image: paint(circle-ripple);
    }
    .el.animating {
          transition: --circle-radius 1s,
                      --circle-color 1s;
          --circle-radius: 300;
          --circle-color: transparent;
    }
</style>
<div class="el" id="el"></div>
<script>
    'use strict'
    CSS.paintWorklet.addModule('registerPaint.js');
    el.addEventListener('click'.e= > {
          el.classList.add('animating');
          el.attributeStyleMap.set('--circle-x', e.offsetX);
          el.attributeStyleMap.set('--circle-y', e.offsetY);
    });
</script>
Copy the code

So we have the following effect:

CSS Babel — PostCSS

After all, CSS Houdini is only JS IN CSS, not pure CSS, so for some new CSS properties, we use words, really have to wait 5 years? And even though there are tools for compatibility writing, vendor prefixes, looping, and native CSS, don’t we still have to rely on CSS preprocessors?

No, we can use the CSS equivalent of Babel — PostCSS

What is PostCSS?

To put it simply, PostCSS is a processor that allows developers to use JS to handle CSS. It has the following five categories of functions:

Improve code readability

Add vendor-specific prefixes to CSS rules using data retrieved from the Can I Use web site. Autoprefixer automatically gets the browser’s popularity and supported attributes, and automatically prefixes CSS rules based on this data.

For example, we enter the following code:

:fullscreen{}Copy the code

It will print:

:-webkit-:full-screen {
}
:-moz-:full-screen {
}
:full-screen {
}
Copy the code

Bring the CSS features of the future to today!

PostCSS Env helps you turn modern CSS syntax into something that most browsers will understand, depending on your target browser or runtime environment to determine the polyfills you need, based on CSSDB implementation.

For example, we enter the following code:

@custom-media --med (width< =50rem);

@media (--med) {
  a{&:hover {
      color: color-mod(black alpha(54%)); }}}Copy the code

It prints:

@media (max-width: 50rem) {
  a:hover  { 
    color: rgba(0.0.0.0.54); }}Copy the code

Ending the Global CSS

CSS modules mean that you never have to worry about naming too common and causing conflicts too common, just use the names that make the most sense.

For example, we enter the following code:

.name {
  color: gray;
}
Copy the code

It prints:

.Logo__name__SVK0g {
  color: gray;
}
Copy the code

Avoid errors in CSS code

Stylelint is a modern CSS code checker by using stylelint to enforce consistency conventions and avoid errors in style sheets. It supports the latest CSS syntax, including CSS-like syntax such as SCSS.

For example, we enter the following code:

a { 
  color: #d3;
}
Copy the code

The console throws an error:

app.css
2:10 Invalid hex color
Copy the code

Powerful grid system

LostGrid uses calc() and the partitioning method you define to create a grid system without passing a lot of parameters.

For example, we enter the following code:

div {
  lost-column: 1/3 
}
Copy the code

It prints:

div {
  width: calc(99.9% * 1/3 -  
  (30px - 30px * 1/3)); 
}
div:nth-child(1n) {
  float: left; 
  margin-right: 30px; 
  clear: none; 
}
div:last-child {
  margin-right: 0; 
}
div:nth-child(3n) {
  margin-right: 0; 
  float: right; 
}
div:nth-child(3n + 1) {
  clear: both; 
}
Copy the code

A peek into the future — CSSDB

CSSDB is the implementation baseline of postCSS-preset – Env, which is the new CSS features and the process in which these features are proposed to become a standard.

CSSDB, like ECMA, has different processes for new attributes. The specific processes are as follows:

  1. Stage 0: Brain storm. Highly unstable and subject to change.
  2. Stage 1: Experiment. It is also very volatile and subject to change, but the proposal has been endorsed by W3C members.
  3. Stage 2: Recognition. Highly unstable and subject to change, but under active investigation.
  4. Stage3: Hug phase. Stable and not changing much, this feature may become standard.
  5. Stage4: Standard stage. The final solution, supported by all major browsers.

This is the implementation baseline postCSS-preset -env relies on, so what if we want to use these stages in our code?

Using my scaffold ying-Template as an example, let’s look at the actual configuration in Webpack:

First we’ll install PostCSS and its plug-ins:

npm install postcss postcss-loader postcss-preset-env postcss-nesting --save-dev
Copy the code

We then enter the following configuration in the Config Configuration Module of WebPack:

module: {
    rules: [{test: /\.css$/,
            include,
            exclude,
            use: [/* Your other loader */ 'postcss-loader']]}}Copy the code

Then create a new postcss.config.js file in the root directory

const postcssConfig = {
    plugins: {
        precss: {},
        'postcss-preset-env': {
            browsers: 'last 2 versions'.// Browser compatible version
            stage: 3 // The phase of the attribute you are using
        },
        'postcss-nesting': {} // Here is the plugin you are using}};module.exports = postcssConfig
Copy the code

That’s it. If you want to see the full configuration, clone my scaffolding: github.com/KRISACHAN/y…

(This is a multi-page Webpack4 scaffolding that integrates Babel 7, Precss 4, typescript3.7, Karma, and ESLint, all of which are commonly used in modern front-end development. If you are interested, check it out.)

We can see the specific compilation results at preset-env.cssdb.org/playground.

The compilation result is shown as follows:

Isn’t that amazing?

The latter

With the popularity of front-end engineering and the demise of the E browser, CSS has grown rapidly, and there have been a number of proposals for mathematical properties recently, but no one knows what the future will be. But overall, the future of CSS looks bright. This article simply shares some modern CSS knowledge, through these knowledge, we can easily write complete and modern CSS code, can create more benefits, I hope you can actively use these knowledge, and can have more thinking and imagination of CSS.

CSS, the future can be expected

source

  1. Developer.mozilla.org/zh-CN/docs/…
  2. oocss.org/
  3. getbem.com/
  4. smacss.com/
  5. sass-lang.com/
  6. lesscss.org/
  7. stylus-lang.com/
  8. Blog. Techbridge. Cc / 2017/05/23 /…
  9. www.smashingmagazine.com/2016/03/hou…
  10. slides.iamvdo.me/waq19/fr/
  11. www.qed42.com/blog/buildi…
  12. www.postcss.com.cn/
  13. Cssdb.org/#staging-pr…
  14. S0dev0to. Icopy. Site/adrianbdesi…

Afterword.

If you like to discuss technology, or have any comments or suggestions on this article, you are welcome to add yu Tou wechat friends to discuss. Of course, Yu Tou also hopes to talk about life, hobbies and things with you. His wechat id is krisChans95