![]() |
CSS Modules are one of the popular techniques that are used for local scoping CSS in JavaScript behavioral applications. In Next.js applications, CSS Modules are mostly used to generate the unique class names for our styles, preventing them from conflicting with the styles from different components or libraries. In this article, we will look into the approaches for Controlling the specificity of CSS Modules in a Next.js App. Approaches for Controlling the Specificity of CSS Modules in a Next.js App
Steps to Create Next.JS applicationCreate the New Next.js Application by following the below commands in the VScode terminal. npx create-next-app css-module-hierarchy Project Structure![]() Approach 1: Combining CSS Modules and Component HierarchiesIn this approach, we are using the natural hierarchy in components to control CSS Modules’ specificity in Next.js App. The components here are paired with their own CSS Module. The ‘Header’ component, features a CSS Module with the classes like “.header” and “.nav”, which controls the layout and style of the header section. The same is done with the ‘Button; component, which ensures specificity and prevents the types to be leaked to the other parts of the app. Syntax:.button { Example: Now, add the below code in the respective files as shown in the above directory structure. Javascript
Javascript
Javascript
CSS
CSS
Step to run the application:Now, run the application by executing the below command in the terminal: npm run dev Output:Approach 2: Using Dynamic Styling with Scoped VariablesIn this approach, we are using the Dynamic Styling with Scoped Variables in which we have created Custom CSS in JavaScript utility which is “scopedVariables.js”. In this the styles for the “ProfileCard” are been specified, incorporating CSS variables that control the styling color. In the “ProfileCard” component, we have used the scoped variables and CSS variables for actually applying the dynamic styling. This component also accepts the props like name, jobTitle, etc. So by injecting the props into the scoped styles, we created component-specific styles that are actually dynamic and also isolated and avoid clashes. Syntax: const generateScopedStyles = (componentName, variableValue) => { Example: Now, add the below code in the respective files as shown in the above directory structure: Javascript
Javascript
Javascript
Step to run the application:Now, run the application by executing the below command in the terminal: npm run dev Output: |
Reffered: https://www.geeksforgeeks.org
CSS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |