Syntactically Awesome Style Sheets
SASS (Syntactically Awesome Stylesheets) is a preprocessor scripting language that is interpreted or compiled into Cascading Style Sheets (CSS). It provides mechanisms for more advanced and succinct ways of writing CSS, offering features that native CSS doesn’t, like variables, nesting, mixins, inheritance, and other powerful directives that make the styling process more efficient and manageable.
The main benefits of using SASS include:
Variables: You can store colors, fonts, or any CSS value you think you’ll want to reuse. This makes your CSS more maintainable and your code more readable.
Nesting: SASS allows you to nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. This makes the styles easier to organize and maintains a clear relationship between the HTML and CSS.
Partials and Import: You can create small CSS pieces in separate files and import them into a single file. This modular approach helps in organizing CSS code better and reusing styles across projects.
Mixins: Mixins allow you to create reusable pieces of CSS code that can be included in other CSS rules. They can take parameters, making your code DRY (Don’t Repeat Yourself) and reducing the amount of code you need to write and maintain.
Inheritance: With SASS, you can share a set of CSS properties from one selector to another, which means you can write generic styles that can be extended as needed.
Advanced Functions: SASS supports functions and control directives (like if-else conditions and loops), allowing for more dynamic and complex stylesheets.
SASS Files
SASS files have .scss or .sass extensions, and they need to be compiled into .css files before they can be used in a website. This compilation can be done via command line tools or through build tools and task runners like Webpack, Gulp, or Grunt.
.scss vs .sass
SCSS (Sassy CSS): This syntax uses the .scss
file extension and is fully compliant with CSS syntax. It uses curly braces {}
and semicolons ;
, much like traditional CSS, making it easier for those familiar with CSS to adapt. This means that any valid CSS stylesheet is also a valid SCSS file with the same meaning. SCSS was designed to close the gap between SASS and CSS, allowing developers to gradually adopt the advanced features of SASS without a steep learning curve.
SASS (Syntactically Awesome Stylesheets): This older syntax uses the .sass
file extension and follows a more concise and indentation-sensitive syntax. It does not use curly braces or semicolons; instead, it relies on the indentation of lines to define the structure of the document. This makes the syntax cleaner and more succinct but can also be a bit harder to grasp for those used to the more verbose CSS syntax.
Installation:
npm i -g sass
Automated compiling of scss files to css:
sass --watch scss/style.scss css/style.css
by running this command, the compiler will automatically compile a .css file to your css/style.css file as you make changes. Don’t edit the output file! Let the compiler do it for you.
SASS Variables
SASS variables are a powerful feature that allows you to store values that you want to reuse throughout your stylesheet. These values can be colors, font sizes, margins, or any other CSS value. You basically define a value once and use it in multiple places. If you need to update that value, you only have to do it once in the variable, and the change will propagate wherever the variable is used.
The syntax for defining a variable in SASS is simple. You start with a dollar sign ($
), followed by the variable name, an assignment operator (:
), and the value. For example:
// Defining variables
$primary-color: #333;
$font-stack: Helvetica, sans-serif;
$base-margin: 15px;
// Using variables
body {
color: $primary-color;
font-family: $font-stack;
margin: $base-margin;
}
Variable names cannot contain spaces. Use hyphens or underscores to separate words within a variable name, e.g., $font-size or $main_color.
SASS variable names are also case-sensitive, so $myVariable and $myvariable would be considered two different variables.
SASS nesting
SASS nesting is a feature that allows you to write CSS selectors within other selectors, mirroring the hierarchical structure of your HTML. This results in more readable and maintainable code, as it visually represents the relationship between HTML elements and their styles more clearly than traditional CSS.
Here’s a basic example of how nesting works in SASS:
nav {
background-color: #eee;
ul {
list-style-type: none;
li {
display: inline-block;
a {
text-decoration: none;
color: #333;
&:hover {
color: #f00;
}
}
}
}
}
The &
symbol is used to reference the parent selector. In the example above, &:hover
refers to the parent a
selector, applying a style when the mouse hovers over the link.
SASS Modules
A SASS module is essentially a file that contains variables, mixins, functions, and/or CSS that can be imported into other SASS files. This system enhances the modularity and maintainability of your styles by allowing you to organize your code into small, manageable pieces and reuse them without polluting the global namespace.
Key Features of SASS Modules
- Encapsulation: Variables, mixins, and functions defined in a module are not automatically visible globally; they must be explicitly imported to be used. This prevents naming conflicts and keeps the global namespace clean.
- Namespaces: When importing a module, its contents can be accessed using the module’s name as a namespace, which helps in distinguishing between functions, mixins, or variables from different modules with the same name.
@use and @forward rules
@use Rule: The @use rule loads mixins, functions, and variables from other Sass files as modules. Once a module is used, its members can be accessed through dot notation, which includes the namespace (the filename by default). For example, if you have a _colors.scss file with a $primary variable, you can use it in another file with @use ‘colors’ and reference the variable as colors.$primary.
@forward Rule: The @forward rule makes all of a module’s members available to be used in another stylesheet that loads it with @use. It’s a way to re-export a module, so it can be used to organize public APIs of your style libraries.
Example:
// _colors.scss file
$primary: blue;
$secondary: green;
If you then wanted to use these colors in another stylesheet, you would do:
// styles.scss file
@use 'colors';
body {
color: colors.$primary;
background-color: colors.$secondary;
}
Mixins
Mixins can accept arguments, making them a flexible tool for generating complex CSS rules that need to be used in multiple places with slight variations. This helps in keeping your CSS DRY (Don’t Repeat Yourself), making your stylesheets more maintainable and easier to read.
Defining and Using Mixins
To define a mixin in SASS, you use the @mixin
directive followed by the name of the mixin and optionally a list of arguments. The body of the mixin contains the CSS rules that you want to reuse. Here's an example of how to define and include a mixin:
// Defining a mixin
@mixin transform($property) {
-webkit-transform: $property;
-ms-transform: $property;
transform: $property;
}
// Using a mixin
.box {
@include transform(rotate(30deg));
}
In this example, a mixin named transform
is defined, which applies a transform property with vendor prefixes for cross-browser compatibility. The @include
directive is then used to include the mixin within a selector, passing in the rotate(30deg)
argument to apply a rotation transformation to elements with the .box
class.
Mixins can also have optional arguments with default values. This allows you to specify common values that can be overridden when necessary:
@mixin box-shadow($x: 0, $y: 0, $blur: 10px, $color: black) {
box-shadow: $x $y $blur $color;
}
.box {
@include box-shadow($y: 2px, $color: rgba(0,0,0,0.5));
}
In this example, the box-shadow
mixin is defined with default values for all its parameters. When including the mixin, you can specify only the arguments you want to change, as shown for the .box
class.
SASS Inheritance
SASS inheritance is a feature that allows you to share a set of CSS properties from one selector to another, using the @extend
directive. This capability enables you to reuse styles efficiently, making your stylesheets more DRY (Don't Repeat Yourself) and maintainable. It's particularly useful for situations where different elements share common styling with slight variations.
How SASS Inheritance Works
To use SASS inheritance, you define a base class that contains the common styles. Other selectors can then extend this base class to inherit its styles, while also adding their own unique properties. The @extend
directive is the key to this functionality.
Example of SASS Inheritance
Consider you have a .btn
class with some basic button styling, and you want .btn-primary
and .btn-secondary
classes to inherit these styles but also have their own specific colors:
// Base button
.btn {
padding: 10px 15px;
border: none;
border-radius: 5px;
font-weight: bold;
cursor: pointer;
}
// Primary button
.btn-primary {
@extend .btn;
background-color: blue;
color: white;
}
// Secondary button
.btn-secondary {
@extend .btn;
background-color: green;
color: white;
}
SASS Functions
You can also use SASS functions for various reasons. For example, you might want to create a function in SASS that decides whether white or black text should be used based on the background color. The idea would be to calculate the luminance of the background color and then determine if white or black text will provide better contrast. A common approach is to use the YIQ color space to decide the color of the text. The YIQ model is used because it takes human perception into account, making the contrast more accessible to the widest range of individuals.
Here’s a simple SASS function that implements this logic:
@function set-text-color($bg-color) {
// Calculate the luminance of the background color
$luminance: (red($bg-color) * 0.299 + green($bg-color) * 0.587 + blue($bg-color) * 0.114) / 255;
// If luminance is greater than a threshold (0.5, medium brightness),
// return black text for better contrast; otherwise, return white.
@if $luminance > 0.5 {
@return black; // Light background, use black text
} @else {
@return white; // Dark background, use white text
}
}
// Example usage
.element {
$bg-color: #3498db; // Example background color
background-color: $bg-color;
color: set-text-color($bg-color); // Set text color based on background
}