Sass : A simplified way to write CSS – Part 3

This is the third post in series on SASS. In my first post, I briefly discussed about SASS and Variables. In my second post I discussed about operators and some important inbuilt functions. Links of earlier posts are

Sass : A simplified way to write CSS – Part 1

Sass : A simplified way to write CSS – Part 2

In my today’s post, We’ll discuss nesting, mixins and inheritance with SASS.

Nesting is very common practice in programming languages and supported in all the major languages in one or other way. Even if we see the normal HTML page then we find that the whole page is structured in a nested manner. Similarly we find it in XAML or even normal aspx page as well. But it is not supported in CSS.

Sass supports nesting. Let’s see via an example

NestedIf we see above code then we see the whole section is defined for navigation bar in a nested manner. Now let’s see the above CSS when it renders on client and looks like

nestedrenderedThe rendered version is above. Here the Sass pre-processor processes the file and converts it that can be understood by the browser. Here all the classes are rendered in separate blocks as required.

Now let’s move to other topic that is Mix-ins. In our CSS files, many times we write the same css style at several places. If we require to change the same then we need to update the same at several places. Let’s see it via an example

mixin-codeIn above code, we have defined a mix-in variable named custom-style and the same variable, we have used in another classes (class1, class2, class3). To use mix-in variable at another places,  use @include keyword as above in the code. Mix-ins can be used in another scenarios as well.

SASS also supports Inheritance. @extend keyword allows us to use the properties of another class. Let’s see it via an example

In this example, say we want to show messages based on response and change the background color based on response type like on error, warning, success etc. This could be written as

ineritanceHere if we see the above code then we find that we have created a class .message and later we used this class in other classes success, error and warning with extend keyword. Just let’s see how it gets rendered.

renderedinheritanceAs it clearly shows that the classes success, error and warning has power of .message class as well. So we can easily use the inheritance feature as well.

So we have seen in last three articles that Sass provides us the capability to use our normal programming techniques that we are using since long, can be used with CSS. This helps us in writing better and organized manner and also helps not to devote much time on normal CSS.

Hope you all have enjoyed this post.