Over a million developers have joined DZone.

Sass Snippets: Compact Syntax for Nested Properties

· Web Dev Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

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

The Web Dev Zone is brought to you by Stormpath—offering a complete, pre-built User Management API for building web and mobile applications, and APIs. Download our new whitepaper: "Build Versus Buy: Customer Identity Management for Web and Mobile Applications".

Topics:

Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}