How to use css modules

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Documentation about css-modules

css-modules/css-modules

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs ( url(. ) ) and @imports are in module request format ( ./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in node_modules ).

CSS Modules compile to a low-level interchange format called ICSS or Interoperable CSS, but are written like normal CSS files:

/* style.css */ .className < color: green; >

When importing the CSS Module from a JS Module, it exports an object with all mappings from local names to global names.

import styles from "./style.css"; // import < className >from "./style.css"; element.innerHTML = '+ styles.className + '">';

For local class names camelCase naming is recommended, but not enforced.

This is recommended because the common alternative, kebab-casing may cause unexpected behavior when trying to access style.class-name as a dot notation. You can still work around kebab-case with bracket notation (eg. style[‘class-name’] ) but style.className is cleaner.

:global switches to global scope for the current selector respective identifier. :global(.xxx) respective @keyframes :global(xxx) declares the stuff in parenthesis in the global scope.

Similarly, :local and :local(. ) for local scope.

If the selector is switched into global mode, global mode is also activated for the rules. (This allows us to make animation: abc; local.)

Example: .localA :global .global-b .global-c :local(.localD.localE) .global-d

It’s possible to compose selectors.

.className < color: green; background: red; > .otherClassName < composes: className; color: yellow; >

There can be multiple composes rules, but composes rules must be before other rules. Extending works only for local-scoped selectors and only if the selector is a single class name. When a class name composes another class name, the CSS Module exports both class names for the local class. This can add up to multiple class names.

It’s possible to compose multiple classes with composes: classNameA classNameB; .

Composing from other files

It’s possible to compose class names from other CSS Modules.

.otherClassName < composes: className from "./style.css"; >

Note that when composing multiple classes from different files the order of appliance is undefined. Make sure to not define different values for the same property in multiple class names from different files when they are composed in a single class.

Note that composing should not form a circular dependency. Elsewise it’s undefined whether properties of a rule override properties of a composed rule. The module system may emit an error.

Best if classes do a single thing and dependencies are hierarchic.

Composing from global class names

It’s possible to compose from global class names.

.otherClassName < composes: globalClassName from global; >

Preprocessors can make it easy to define a block global or local.

:global < .global-class-name < color: green; > >

modular and reusable CSS!

  • 04/2015: placeholders feature in css-loader (webpack) allows local scoped selectors (later renamed to local scope ) by @sokra
  • 05/2015: postcss-local-scope enables local scope by default (see blog post) by @markdalgleish
  • 05/2015: extends feature in css-loader allow to compose local or imported class names by @sokra
  • 05/2015: First CSS Modules spec document and github organization with @sokra, @markdalgleish and @geelen
  • 06/2015: extends renamed to composes
  • 06/2015: PostCSS transformations to transform CSS Modules into an intermediate format (ICSS)
  • 06/2015: Spec for ICSS as common implementation format for multiple module systems by @geelen
  • 06/2015: Implementation for jspm by @geelen and @guybedford
  • 06/2015: Implementation for browserify by @joshwnj, @joshgillies and @markdalgleish
  • 06/2015: webpack’s css-loader implementation updated to latest spec by @sokra

Webpack’s css-loader in module mode replaces every local-scoped identifier with a global unique name (hashed from module name and local identifier by default) and exports the used identifier.

Extending adds the source class name(s) to the exports.

Extending from other modules first imports the other module and then adds the class name(s) to the exports.

Server-side and static websites

PostCSS-Modules allows to use CSS Modules for static builds and the server side with Ruby, PHP or any other language or framework.

Источник

Adding a CSS Modules Stylesheet

Note: this feature is available with react-scripts@2.0.0 and higher.

This project supports CSS Modules alongside regular stylesheets using the [name].module.css file naming convention. CSS Modules allows the scoping of CSS by automatically creating a unique classname of the format [filename]\_[classname]\_\_[hash] .

Tip: Should you want to preprocess a stylesheet with Sass then make sure to follow the installation instructions and then change the stylesheet file extension as follows: [name].module.scss or [name].module.sass .

CSS Modules let you use the same CSS class name in different files without worrying about naming clashes. Learn more about CSS Modules here.

Button.module.css ​

.error   background-color: red; > 

another-stylesheet.css ​

Button.js ​

import React,  Component > from 'react'; import styles from './Button.module.css'; // Import css modules stylesheet as styles import './another-stylesheet.css'; // Import regular stylesheet  class Button extends Component   render()   // reference as a js object return button className=styles.error>>Error Button/button>; > > 

Result​

No clashes from other .error class names

  button class="Button_error_ax7yz">Error Buttonbutton> 

This is an optional feature. Regular stylesheets and CSS files are fully supported. CSS Modules are turned on for files ending with the .module.css extension.

Источник

How to Style React Components Using CSS Modules

Split your monolithic CSS code into small, reusable pieces with the help of CSS modules.

Gray laptop computer showing css in shallow focus photography

Readers like you help support MUO. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

CSS modules provide a way to locally scope CSS class names. You don’t have to worry about overriding styles when you use the same class name.

Find out how CSS modules work, why you should use them, and how to implement them in a React project.

What Are CSS Modules?

The CSS modules docs describe a CSS module as a CSS file whose class names are locally scoped by default. This means you can address CSS variables with the same name in different CSS files.

You write CSS module classes just like normal classes. Then the compiler generates unique class names before sending the CSS to the browser.

For example, consider the following .btn class in a file called styles.modules.css:

.btn width: 90px; 
height: 40px;
padding: 10px 20px;
>

To use this file, you have to import it into a JavaScript file.

import styles from "./styles.module.js" 

Now, to reference the .btn class and make it available in an element, you would use the class as shown below:

The build process will replace the CSS class with a unique name of the format like _styles__btn_118346908.

The uniqueness of the class names means that, even if you use the same class name for different components, they will not collide. You can guarantee greater code independence since you can store a component’s CSS styles in a single file, specific to that component.

This simplifies debugging, especially if you are working with multiple stylesheets. You’ll only need to track down the CSS module for a particular component.

CSS modules also allow you to combine multiple classes through the composes keyword. For example, consider the following .btn class above. You could “extend” that class in other classes using composes.

For a submit button, you could have:

.btn /* styles */
>

.submit composes: btn;
background-color: green;
color:#FFFFFF
>

This combines the .btn and the .submit classes. You can also compose styles from another CSS module like this:

.submit composes:primary from "./colors.css" 
background-color: green;
>

Note that you must write the composes rule before other rules.

How to Use CSS Modules in React

How you use CSS modules in React depends on how you create the React application.

If you use create-react-app, CSS modules are set up out of the box. However, if you are going to create the application from scratch, you will need to configure CSS modules with a compiler like webpack.

To follow along with this tutorial, you should have:

  • Node installed on your machine.
  • A basic understanding of ES6 modules.
  • A basic understanding of React.

Creating a React Application

To keep things simple, you can use create-react-app to scaffold a React app.

Run this command to create a new React project called react-css-modules:

npx create-react-app react-css-modules

This will generate a new file called react-css-modules with all the dependencies required to get started with React.

Creating a Button Component

You will create a Button component and a CSS module called Button.module.css in this step. In the src folder, create a new folder called Components. In that folder create another folder called Button. You will add the Button component and its styles in this folder.

Navigate to src/Components/Button and create Button.js.

export default function Button( ) return ( 
button>Submit button>
)
>

Next, create a new file called Button.module.css and add the following.

.btn width: 90px; 
height: 40px;
padding: 10px 20px;
border-radius: 4px;
border: none;
>

To use this class in the Button component, import it as styles and reference it in the class name of the button element like this:

import styles from "./Button.module.css" 

export default function Button( ) return (
button className= >Submit button>
)
>

This is a simple example that shows how to use a single class. You may want to share styles across different components or even combine classes. For this, you can use the composes keyword as previously mentioned in this article.

Using Composition

First, modify the Button component with the following code.

import styles from "./Button.module.css" 

export default function Button("primary", label="Button">) return (
button className= > button>
)
>

This code makes the Button component more dynamic by accepting a type value as a prop. This type will determine the class name applied to the button element. So if the button is a submit button, the class name will be “submit”. If it is “error”, the class name will be “error”, and so on.

Источник

Читайте также:  Your Title Here
Оцените статью