Sass (Syntactically Awesome Stylesheets) is a preprocessor scripting language that is interpreted or compiled into CSS. It introduces features not available in regular CSS, making your stylesheets more efficient and maintainable.
Start by installing Sass using npm (Node Package Manager) in your project.
npm install -g sass
Save your styles with a '.scss'
extension, indicating it’s a Sass file.
// style.scss
body {
background-color: #f0f0f0;
}
Compile your Sass file into CSS using the terminal.
sass style.scss style.css
Declare variables for reusable values.
$primary-color: #3498db;
.button {
background-color: $primary-color;
}
Nest selectors for better organization.
.container {
width: 100%;
.header {
background-color: $primary-color;
}
}
Create reusable blocks of styles with mixins.
@mixin border-radius($radius) {
border-radius: $radius;
}
.box {
@include border-radius(10px);
}
Use functions to perform calculations or manipulate values.
@function calculate-width($columns, $column-width) {
@return $columns * $column-width;
}
.container {
width: calculate-width(12, 60px);
}
Break your styles into smaller files called partials (start with an underscore '_'
).
// _variables.scss
$primary-color: #3498db;
// style.scss
@import 'variables';
.button {
background-color: $primary-color;
}
Share styles between selectors using the '@extend'
directive.
.error {
border: 1px solid red;
}
.fatal-error {
@extend .error;
font-weight: bold;
}
Use @if'
, '@else if'
, and '@else'
for conditional styles.
$theme: light;
.container {
@if $theme == light {
background-color: #f0f0f0;
} @else {
background-color: #333;
color: #fff;
}
}
Refer to the parent selector within nested elements.
.button.
&:hover.
background-color: darken($primary-color, 10%).
.
.
Define styles without outputting actual CSS until extended.
%placeholder.
font-weight: bold.
.
.title.
@extend %placeholder.
Use these for conditional styles.
$theme: light.
.container.
@if $theme == light.
background-color: #f0f0f0.
@else.
background-color: #333.
color: #fff.
.
.
Iterate through lists or generate styles dynamically.
@for $i from 1 through 3.
.item#{$i}.
opacity: 0.2 * $i.
.
.
Sass is a robust tool that goes beyond basic styling, offering advanced features like mixins, functions, and control directives. By mastering these concepts, you can write cleaner, more modular stylesheets, enhancing your CSS development workflow. Continue experimenting and incorporating Sass into your projects for efficient and maintainable styling. Happy coding! ❤️