Search

Dark theme | Light theme

February 15, 2013

Sass Snippets: Compact Syntax for Nested Properties

In CSS we can see properties that start with the same name, followed by a hyphen and then the rest of the name. For example we have the padding-top, padding-right, padding-bottom and padding-left properties. We can use the shorthand syntax in this case (padding: 0 0 10px 20px;) or we type each property with the complete name:

padding-top: 0;
padding-right: 0;
padding-bottom: 10px;
padding-left: 20px;

With Sass we can use a different syntax for these kind of properties. We only have to define the common part of the property name and in a block we can define the specific properties. The name is followed by a colon (:) instead of a hyphen (-). In the following sample we define a couple of text- and padding- properties:

// nested-properties.scss

h1 {
    text: {
        align: 'left';
        transformation: 'capatalize';
        indent: 20px;
    }
}

p {
    // Simple variable for padding.
    $padding: 20px;
    
    padding: {
        left: $padding;

        // Calculate with padding variable:
        bottom: $padding / 2;
    }
}

This results in the following CSS:

h1 {
  text-align: 'left';
  text-transformation: 'capatalize';
  text-indent: 20px;
}

p {
  padding-left: 20px;
  padding-bottom: 10px;
}

Samples written with Sass 3.2.5