takeaway
The first lesson most people learn about web development is separation of concerns. That is, HTML is responsible for the basic structure of the web page, CSS is responsible for the style effect of the web page, JS is responsible for the behavior function of the web page.
To put it simply, do not use inline, but bring it in externally via
<div id="demo" style="color: blue;">
hello world
</div>
Copy the code
Pain points of traditional CSS
With declarative syntax, CSS can be maintained independently and loosely coupled to HTML. However, traditional CSS also has many problems.
- Global scope. Once CSS styles are in effect, they are applied globally, causing all kinds of conflicts. To avoid collisions, complex ID selectors and class selectors are often over-relied on.
- Dependency issues. Typically, web pages introduce multiple CSS style files, so files that have already been introduced may have an impact on the styles generated by later introduced files.
- Style clearance. Because too complex ID and class selectors are often written to avoid style conflicts, it can be difficult to find and clean up a CSS style when it is no longer needed.
- Variable sharing. It is very difficult for CSS and JS to share data. As a result, it is sometimes possible to forget to modify styles with JS because of the complexity of the selector.
- Break the quarantine. When a set of styles is designed, but new style requirements are created, it is inevitable that the newly generated styles will affect the original styles.
The solution
- CSS modular. Vue throughscoped CSSEnsures that CSS styles only apply to the current component. Tags will not be generated repeatedly
data
Attributes (such as:data-v-69f2668b
) to indicate his uniqueness. It is also generated on compiled generated CSSdata
Property selectors (e.g[data-v-69f2668b]
) to privatize styles.
- The CSS in JS. The React component structure requires HTML, CSS, and JavaScript to be written together. Many of the problems of CSS mentioned above can be solved by borrowing JS.
<div id="demo" style="color: blue;">
hello world
</div>
Copy the code
const style = {
'color': 'blue'}; ReactDOM.render(<h1 style={style}>
hello world
</h1>.document.getElementById('example'));Copy the code
- The utility – class. TailwindCSS for example, through CSS atomization to achieve pure CSS solutions. By combining existing classes, you can effectively avoid using complex selectors.
The resources
Technology | CSS – in – JS: heaven and earth of the technical scheme of a controversial vue of CSS scope, scoped pit point of vue CSS in JS profile React: CSS in JS – NationJS