skip to Main Content

As I’m coming from Vuejs background and starting with Nextjs now, I want to scope my css for each of my component like- Navbar instead of using it inside Globas.css, is there a way to do that?

I’m using tailwind css library alongside it.

I did try by making individual css files for my each component like Angular and import it inside my each component but it does not work out like as expected.

This is how my current folder structure looks like-

enter image description here

3

Answers


  1. You can use CSS Modules or styled-components such as emotion to scope your css to components in React. I don’t think you’ll need to if you use tailwind because of the utility classes it serves.

    Login or Signup to reply.
  2. You need to use CSS modules. Create your-component.module.scss or css file and import it like

    import styles from './your-component.module.scss';
    
    ...
     <div className={styles.yourClass}> ... </div>
    ...
    

    Since you are coming from Vue, CSS-in-JS might suit you better. You have many options such as StyledComponents, Linaria, Emotion, etc.

    Login or Signup to reply.
  3. You can use either use styled components or CSS modules for that.
    Here’s how to use CSS modules to Navbar.jsx

    Create Navbar.module.css file.

    .navbar{
        display: flex;
        justify-content: center;
    }
    .logo{
        display: inline-block;
    }
    
    //add your CSS classes

    In Navbar.jsx file import the CSS file

    import classes from './Navbar.module.css'
    

    to use those classes in `Navbar.jsx’

    <nav className={classes.navbar}>...</nav>;
    

    The class variable will contain CSS classes as properties.

    Lean more about CSS Modules

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search