What is Sass?

Sass (Syntactically Awesome Style Sheets) is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). It extends CSS with features like variables, nested rules, mixins, and functions, making it easier to write and maintain stylesheets.

Key Features of Sass

  • Variables: Sass allows you to define variables that can store values such as colors, fonts, or any CSS value. This makes it easy to reuse values throughout your stylesheet.
  • Nesting: You can nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. This makes the code more readable and organized.
  • Mixins: Mixins allow you to create reusable chunks of CSS that can be included in other selectors. This is useful for applying styles that are used multiple times.
  • Partials and Import: Sass allows you to break your CSS into smaller, manageable pieces using partials, which can be imported into a main stylesheet.
  • Functions and Operations: Sass provides built-in functions and allows you to perform operations on values, making it powerful for dynamic styling.

Sample Code

1. Variables


$primary-color: #3498db;
$font-stack: 'Helvetica Neue', sans-serif;

body {
font-family: $font-stack;
background-color: $primary-color;
}

2. Nesting


nav {
ul {
list-style: none;
}

li {
display: inline-block;
margin-right: 20px;
}

a {
text-decoration: none;
color: white;
}
}

3. Mixins


@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}

.button {
@include border-radius(5px);
background-color: $primary-color;
color: white;
}

4. Partials and Import

To create a partial, you can create a file named _variables.scss:


$primary-color: #3498db;
$font-stack: 'Helvetica Neue', sans-serif;

Then, in your main Sass file, you can import it:


@import 'variables';

body {
font-family: $font-stack;
background-color: $primary-color;
}

Conclusion

Sass is a powerful tool that enhances the capabilities of CSS, making it easier to write and maintain stylesheets. By using features like variables, nesting, and mixins, developers can create more organized and efficient styles for their web projects.