Skip to content

Instantly share code, notes, and snippets.

@IsTheJack
Created February 6, 2020 17:16
Show Gist options
  • Save IsTheJack/b686d04c5896296af310424090e140f8 to your computer and use it in GitHub Desktop.
Save IsTheJack/b686d04c5896296af310424090e140f8 to your computer and use it in GitHub Desktop.
How to protect the CSS scope properly using SASS and BEM

How to protect the CSS scope properly using SASS and BEM

Some truths about css:

  • CSS works in cascade
  • CSS works globally

Some Problems with Cascade

  • You could have problems with specificities
  • You could have problems with unexpected changes

Some problems with Cascade and Global CSS:

  • You'll have problems with specificities
  • You'll have problems with unexpected change
  • You'll lose control over your CSS

To solve/avoid those problems, you can use CSS with BEM inside the React project.

It's very simple:

  • Every component should have a unique name inside the project
  • Every root element from a react component should have the same name as className (in snake case)
  • Every SCSS file should have the component name as the scope, and every CSS rule should be written inside that scope

Let's imagine that you'll create the component SuperCard.

About the component file:

  • should be called SuperCard.tsx
  • the component name should be SuperCard
  • the root element should have the same name as the component, but in snake case super-card

Eg.

import * as React from 'react

// import the scss file
import './SuperCard.scss'

// should be SuperCard
const SuperCard = () => (
  // Should be super-card
  <div className="super-card">
    // Obbey the BEM pattern
    <div className="super-card__some-children-element" />
  </div>
)

export default SuperCard

About the CSS file:

  • Should be called SuperCard.scss
  • Should have the super-card as the scope
  • All children rules should be inside the scope
  • Should follow the BEM pattern
.super-card {
  // rules
  &__some-children-element {
    // children rules
  }
}

Following those steps, you'll always protect the scope of your components.

Cheers!

@IsTheJack
Copy link
Author

In some projects instead of snake-case you'll see the block name as UpperCamelCase

.SuperCard {
  // rules
  &__some-children-element {
    // children rules
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment