Detuned
Detuned

Reputation: 3758

CSS modules nested selectors

I have the following convention for name spacing my app and components:

<div id="app-name">

  <ul class="list">
    <li>item</li>
  </ul>

</div>

#app-name {

  .list {
    margin: 0;
  }

}

I'd like to use CSS modules, however, I'm not sure how one would go about converting this and keep the same specificity of app and component name spacing. I understand I could simply omit the entire #app-name ID but I'd like this sort of specificity.

Thoughts?

Upvotes: 4

Views: 5813

Answers (4)

Gil Epshtain
Gil Epshtain

Reputation: 9831

Nothing spicial, just nest your element the same way you nest your selectors

// style.module.scss
.container {
  .list {
    .item {
      background: red;
    } 
  }
}

// component.tsx
import styles from './style.module.scss';

export MyComponent: React.FunctionComponent = () => (
  <div className={styles.container}>
    <div className={styles.list}>
      <div className={styles.item}>
       Hello :-)
      </div>
    </div>
  </div>
)

Upvotes: 0

Lewis
Lewis

Reputation: 3415

I'm not sure if it works in all implementations but in Next.js you can prefix a css selector with :global to allow it to target a standard class name:

#app-name {
  :global .list {
    margin: 0;
  }
}

Credit to ctsstc on GitHub for discovering this.

Upvotes: 2

Rich
Rich

Reputation: 4248

You need to reference both selectors to the imported style module.

App.tsx

import style from './App.module.scss';
function App() {
  return (
    <div id={style['app-name']}>
      <ul className={style.list}>
        <li>item</li>
      </ul>
    </div>
  )
}

App.module.scss

#app-name {
  .list {
    margin: 0;
  }
}

This has been a known issue before, and they tried to create workarounds in order to achieve the desired output. Luckily this has been resolved.

Upvotes: 6

Sumit patel
Sumit patel

Reputation: 3903

Try This

#app-name .list {
    margin: 0;
  }

Snippet Example Below

 #app-name .list {
    margin: 0;
  }
<div id="app-name">

  <ul class="list">
    <li>item</li>
  </ul>

</div>

Upvotes: -3

Related Questions