CLOSE
Introduction
When working on CSS for large projects, maintaining readability and reusability is crucial. This is where sass / scss and BEM (Block Element Modifier) come into play. Let's see how they can be used together effectively.
Sass/SCSS
Sass (Syntactically Awesome Style Sheets) is a CSS preprocessor that adds power and elegance to the basic language. SCSS is a syntax of Sass which is fully compatible with CSS.
Example:
$primary-color: #3498db;
$font-stack: Roboto, sans-serif;
.button {
background-color: $primary-color;
font-family: $font-stack;
padding: 16px 24px;
border: none;
color: white;
cursor: pointer;
&:hover {
background-color: darken($primary-color, 10%);
}
}
BEM (Block Element Modifier)
BEM is a methodology that helps you create reusable components and code sharing in front-end development. It stands for Block Element Modifier.
Example:
- Block: The main container (e.g., button).
- Element: A part of the block that performs a certain function.
- Modifier: A flag for a block or element to change its appearance or behavior
<button class="button button--primary">
<span class="button__icon"></span>
Click Me
</button>
SCSS Implementation:
.button {
&--primary {
background-color: $primary-color;
}
&__icon {
margin-right: 8px;
}
}
When combining Sass/SCSS with BEM, you get organized and maintainable CSS. Here's a practical example:
$primary-color: #3498db;
$secondary-color: #2ecc71;
.button {
display: inline-flex;
align-items: center;
padding: 16px 24px;
border: none;
color: white;
cursor: pointer;
&--primary {
background-color: $primary-color;
&:hover {
background-color: darken($primary-color, 10%);
}
}
&--secondary {
background-color: $secondary-color;
&:hover {
background-color: darken($secondary-color, 10%);
}
}
&__icon {
margin-right: 8px;
}
}
<button class="button button--primary">
<span class="button__icon">🔍</span>
Search
</button>
<button class="button button--secondary">
<span class="button__icon">➕</span>
Add
</button>
By using Sass/SCSS and BEM together, you can achieve clean, organized, and maintainable styles for your web projects.
Thanks for reading!