Home>Article>Web Front-end> What are CSS Modules? Take a look!

What are CSS Modules? Take a look!

青灯夜游
青灯夜游 forward
2021-02-14 09:29:55 2507browse

What are CSS Modules? Take a look!

I interviewed with a company in April this year.

During the technical interview, I was asked if I had understood CSS Module. I said I had not,

He continued to ask, what should you do when you give class names to components and elements during normal development?
I said to add specific prefixes to elements and components, so as to ensure that the class names written by you will not conflict with the class names written by other colleagues.

Then it stopped, and I was asked a lot of questions about React principles and things like that and passed the interview.

Today we will explain to him what CSS Modules are, so that it will be more clear.

[Recommended tutorial:CSS video tutorial]

First let’s look at a picture:

A picture to understand the working principle of CSS Modules:
What are CSS Modules? Take a look!
When we coded ourselves, we had two files, one was the ProductList.less file and the other was the ProductList.jsx file
After the build, the less file will be converted into the file with the blue title .

It can be seen from this:

  • button class will be renamed to ProductList_button_1FU0u after it is built. button is the local name, and ProductList_button_1FU0u is the global name.You can use short, descriptive names without worrying about naming conflicts.

Then all you have to do is write .button {…} in the css/less file and reference it through styles.button in the component.

Define global CSS

CSS Modules are local scoped by default. If you want to declare a global rule, you can use the :global syntax.

For example:

.title { color: red; } :global(.title) { color: green; }

When quoting:

 // red  // green
classnames Package

In some complex scenarios, one element may correspond to multiple classNames, and Each className determines whether to appear based on some conditions. At this time, the classnames library is very useful.

import classnames from 'classnames'; const App = (props) => { const cls = classnames({ btn: true, btnLarge: props.type === 'submit', btnSmall: props.type === 'edit', }); return 
; }

In this way, if different types are passed to the App component, different className combinations will be returned:

 // btn btnLarge  // btn btnSmall

For more programming-related knowledge, please visit:Programming Teaching! !

The above is the detailed content of What are CSS Modules? Take a look!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete