SCSS Basics

Preprocessing

  1. Enable Live Sass Compiler extension on Visual Studio Code
  2. Click on “Watch Sass” icon

Variables

Use the $ sign to indicate a variable, and then use it afterward. Storing variables to reuse helps with consistency and branding.

$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

Nesting

Nest CSS the same way as your HTML is nested. Take note that overly nested rules can be hard to maintain and is a bad practice.

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

_Partials

You can modularize the CSS by importing (with @import) partial Sass files (_partial.scss). The underscore indicates a partial file not to be generated into CSS.

@import

Sass @import circumvents the HTTP requests needed for CSS @import by combining them when generating the CSS file.

// _reset.scss, the file to be imported

html,
body,
ul,
ol {
  margin:  0;
  padding: 0;
}
// base.scss

@import 'reset';

body {
  font: 100% Helvetica, sans-serif;
  background-color: #efefef;
}

@mixin

Mixins let you make groups of CSS declaration under a mixin name. Suitable for vendor prefixes. Similar to JS functions. To use it, use @include mixin-name(variable);

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}

.box { @include transform(rotate(30deg)); }

 

@extend

@extend extends/ shares CSS properties of one selector to another. Use placeholders (% sign in front) to ensure you are not extending a class nested elsewhere.

/* This CSS will print because %message-shared is extended. */
%message-shared {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

// This CSS won't print because %equal-heights is never extended.
%equal-heights {
  display: flex;
  flex-wrap: wrap;
}

.message {
  @extend %message-shared;
}

.success {
  @extend %message-shared;
  border-color: green;
}

.error {
  @extend %message-shared;
  border-color: red;
}

.warning {
  @extend %message-shared;
  border-color: yellow;
}

 

Math

You can use standard math operators like +-*/, and % for calculations in Sass.

.container {
  width: 100%;
}

article[role="main"] {
  float: left;
  width: 600px / 960px * 100%;
}

aside[role="complementary"] {
  float: right;
  width: 300px / 960px * 100%;
}

Leave a comment

Design a site like this with WordPress.com
Get started