Clean β’ Professional
Modern React applications often require advanced styling techniques like variables, nesting, mixins, and modular styles. Sass/SCSS is a powerful CSS preprocessor that extends CSS with these capabilities, making styles more maintainable, reusable, and readable.
If youβre using Create React App or Vite, you can install Sass easily:
.scss files into CSS.npm install sass
# or
yarn add sass
Create a file App.scss:
$primary-color: #007bff;
$secondary-color: #6c757d;
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
.button {
padding: 10px 20px;
border-radius: 5px;
border: none;
cursor: pointer;
&--primary {
background-color: $primary-color;
color: white;
&:hover {
background-color: darken($primary-color, 10%);
}
}
&--secondary {
background-color: $secondary-color;
color: white;
&:hover {
background-color: darken($secondary-color, 10%);
}
}
}
import React from "react";
import "./App.scss";
export default function App() {
return (
<div>
<button className="button button--primary">Primary</button>
<button className="button button--secondary">Secondary</button>
</div>
);
}
$primary-color and $secondary-color are Sass variables.&--primary and &--secondary use nesting for cleaner CSS.darken() is a Sass function to adjust color brightness.Mixins
Mixins allow reusable blocks of styles:
@mixin flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.container {
@include flex-center;
height: 100vh;
}
Partials & Imports
Split styles into multiple files for organization:
// _variables.scss
$primary-color: #007bff;
// _buttons.scss
@import 'variables';
.button {
background-color: $primary-color;
}
Functions
Create reusable logic for styles:
@function spacing($factor) {
@return $factor * 8px;
}
.card {
margin: spacing(2);
padding: spacing(3);
}
Nesting
Write hierarchical styles cleanly:
.nav {
ul {
list-style: none;
li {
display: inline-block;
margin-right: 20px;
}
}
}