Home>Article>Web Front-end> 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.
[Recommended tutorial:CSS video tutorial]
A picture to understand the working principle of CSS Modules:
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:
Then all you have to do is write .button {…} in the css/less file and reference it through styles.button in the component.
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
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!