Home >Web Front-end >CSS Tutorial >What is css modularity? How to implement css modularity
The content of this article is about what is CSS modularity? The implementation method of CSS modularization has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
CSS Modularity
CSS (Cascading Style Sheets) has been determined from the beginning that it cannot be programmed, and is not even an interpreted language. It can only be used as a simple Cascading style sheets, which format HTML elements.
But with the development of front-end, front-end projects have become increasingly large and complex, and the community has been exploring how to manage front-end code (js/css/html) and Resources (images, fonts, ...).
In this process, the community has explored the modularity of js (amd, commonjs, es6). Now it is easy to develop large projects with js, but the modularity of css has not yet been particularly popular.
This is the earliest implementation of CSS modularization, and it is also the most important way. Many components and developers are now developed in this way. of.
Grouped modularization is to use naming, with different prefixes representing different meanings, to achieve style grouping and file chunking to achieve the purpose of modularization.
For example:
# 目录结构 |-- one/page/css/ 某个页面的 css 目录 |-- common.css 通用的 css |-- page1/ 单页面1 |-- section1.css 区域1 css |-- section2.css 区域2 css |-- page2/ 单页面2 |-- ... # common.css 文件 .c-el-1 { ... } .c-el-2 { ... } ... # page1/section1.css 文件 .page1-section1 { ... } .page1-section1 .el-1 { ... } .page1-section1 .el-2 { ... } ... # page1/section2.css 文件 .page1-section2 { ... } .page1-section2 .el-1 { ... } .page1-section2 .el-2 { ... } ...
This method is not modular in the true sense, because it cannot avoid global conflicts, but native css I don't have the ability to program, so this problem is unavoidable. Although grouping is not modular in the true sense, this method does not break away from css. It is a native mechanism, so many third-party components use this method when exporting css files.
For example, the ant- prefix is used in the css exported by ant-design, and the mui- prefix is used in the css exported by mui.
css Named grouping has been practiced for a long time. It has been around since the birth of CSS, so the community has developed very maturely, such as NetEase’s CSS specification framework NEC. H-ui.
Supplement:
A css file should not be too large, you can use @import to divide the file into blocks;
Try not to use #id [attr] for style rendering, but try to use it as much as possible .class;
When using js library to operate dom, try not to use .class, try to use #id data-set, such as $('#main'), $('[data-tab="1 "]').
<ul> <li data-tab="1">tab1</li> <li data-tab="2">tab2</li> </ul> <p data-tab-container="1"></p> <p data-tab-container="2"></p>
Because css is not a programming language, it cannot declare variables, functions, make judgments, loops and calculations, and cannot nest, so this makes the writing style An inefficient and boring job.
In order to solve this problem, the community mainly derived two expansion languages less and sass during exploration. They are compatible with CSS and expand the programming functions. They mainly bring the following features:
You can declare variables and functions, and perform some simple calculations, judgments, and loops;
You can nest selectors, which saves writing content and is more readable;
.page1-section1 { ... .el-1 { ... .el-1-1 { ... } } .el-2 { ... } }
@import avoids repeated import problems, so you can import other files with confidence.
From a modular perspective, less and sass only expand the functions of css, but do not implement modularization at the language level because the problem of global naming conflicts still exists.
If we want to make CSS have a modular function in the true sense, we cannot consider it from the language level for the time being, so we can only use tools from the perspective of implementation.
Currently a better way is to use js to load the css file, export the css content as an object, use js to render the entire dom tree and match the corresponding styles to the corresponding elements. In this process , we have the opportunity to do additional processing on css to achieve modularity.
For example:
Source file
# style.css 文件 .className { color: green; } # js 文件 import styles from "./style.css"; element.innerHTML = '<p class="' + styles.className + '">Hello!</p>';
Actual effect
# style.css 文件 ._23_aKvs-b8bW2Vg3fwHozO { color: green; } # DOM <p class="_23_aKvs-b8bW2Vg3fwHozO">Hello!</p>
In this conversion process, a globally unique base64 string is generated based on the location and content of the file, and the original name is replaced to avoid the problem of global naming conflicts, thus achieving the purpose of modularization. Therefore, there is no global style conflict problem during the development process.
# common.css 文件 .container { ... } .el1 { ... } .el2 { ... } ... # page1/section1.css 文件 .container { ... } .title { ... } .content { ... } ... # page2/section1.css 文件 .container { ... } .title { ... } .content { ... } ...
For the definition of css modularity, see css-modules. The main requirements for writing css are:
1. .class should be used instead of #id [attr] (because there is only . class can be exported as an attribute of an object);
2. It is recommended to write in .className instead of .class-name (the former can be accessed through styles.className, and the latter needs to be accessed through styles['class-name'] to access).
For more features, please view css-modules.
Of course, this function requires the support of the build tool. If you use webpack to build the project, you can use css-loader and set options.modules to true to use the modular function.
With the development of front-end componentization, the update of componentization frameworks, such as react and vue, has slowly developed into the entire The resources of the component are encapsulated and only one object is exposed to the outside world. The caller does not need to care about the internal implementation and resources of the component. It is enough to directly call this object.
比如(以 react 为例),一个 Welcome 组件,包括一个 js 文件、一个 css 文件、图片:
# Welcome 组件 |-- welcome.js |-- welcome.css |-- images/
在 welcome.js
中便可如下加载(使用“导出为 js 对象”的 css 模块化):
import styles from './welcome.css'; import image1 from './images/1.jpg';
其实,还有另外一种思路,就是将 css 内置 js 中,成为 js 的一部分。
这样做的目的,一是 css 的模块化,二是直接绑定到组件上。
比如,material-ui、styled-jsx、jss、vue style scoped 便是使用的这种方式。
这种方式的实现有很多种,这里主要介绍一下 styled-jsx。
styled-jsx 的原理是根据当前文件的位置、内容生成一个全局唯一的标识,然后把这个标识追加到组件每一个元素上,每一个样式选择器上,达到模块化的目的。
可以参考官方文档,查看详细的用法,我在这里给个例子:
npm install --save styled-jsx
.babelrc
){ "plugins": [ "styled-jsx/babel" ] }
hello.js
export default () => ( <div className={'container'}> <p className={'hello'}>Hello! Hello!</p> <div id={'hi'}>Hi!</div> <style jsx>{` .container { color: blue; } p:first-child { color: red; } .hello { color: yellow; } #hi { color: green; } `}</style> </div> )
babel path/to/hello.js -d target/dir
转码后的文件
import _JSXStyle from 'styled-jsx/style'; export default () => ( <div className={'jsx-234963469' + ' ' + 'container'}> <p className={'jsx-234963469' + ' ' + 'hello'}>Hello! Hello!</p> <div id={'hi'} className={"jsx-234963469"}>Hi!</div> <_JSXStyle styleId={"234963469"} css={".container.jsx-234963469{color:blue;}p.jsx-234963469:first-child{color:red;}.hello.jsx-234963469{color:yellow;}#hi.jsx-234963469{color:green;}"} /> </div> );
实际渲染效果
<style type="text/css" data-styled-jsx=""> .container.jsx-234963469{ color:blue; } p.jsx-234963469:first-child{ color:red; } .hello.jsx-234963469{ color:yellow; } #hi.jsx-234963469{ color:green; } </style> <div class="jsx-234963469 container"> <p class="jsx-234963469 hello">Hello! Hello!</p> <div id="hi" class="jsx-234963469">Hi!</div> </div>
以上就是本篇文章的全部内容了,更多css相关内容请关注php中文网的css教程栏目。
The above is the detailed content of What is css modularity? How to implement css modularity. For more information, please follow other related articles on the PHP Chinese website!