Category - Tutorials

Working with SASS and Visual Studio

This is a tutorial on how to use SASS, which is a CSS pre-processor, and how to integrate it into a Visual Studio's MVC project.

What is SASS?

Stands for Syntactically Awesome Style Sheets. Basically it is a scripting language that can be used to generate CSS files. It had a rocky start when it was first introduced in 2007, but it's newest version which has the file extension of .scss stands for (Sassy CSS) has cleaned up a lot of the hiccups and created an extremely efficient and comfortable scripting language for those familiar with CSS. The best part about SASS is that you can take all of your normal CSS code and paste it into the .scss file and it'll work without any problems. A .scss file is really just a "superset" of CSS.

So you only have to be as SASSY as you want! Wow, that looks as bad typed out as it sounded in my head! ;)

What is COMPASS?

Compass is essentially a bunch of pre-built SASS mixins (functions) that you can easily integrate.

Prerequisites:

  • Full Version of Visual Studios (professional or ultimate). The express version will not do as you are not able to install extensions.
  • A good fundamental knowledge of html, css and loops.

For this walkthrough I'll be using Visual Studios 2013 Ultimate and programming in C#

  1. Setup

    1. Let's start by installing an extension into your Visual Studios. Since the plugin we will be installing is not a Microsoft plugin, you can not add this with the Express version, so open up a full version of Visual Studio (professional or ultimate) and select Tools -> Extensions and Updates -> Online -> Search for "Mindscape Web Workbench" -> Install.

    2. Next, let's get a project created. I'll be listing the steps for using Visual Studio 2013. Click on File -> New Project -> (Your preferred Language such as C#) -> Web -> ASP.Net Web Application. Enter the name and solution name as: SassExample. Next choose MVC then click OK.

    3. Now we need to setup Sass/Compass support.

      Right click on the world icon for SassExample -> Choose "Setup Compass Project" -> You can choose to not view the Guide to working with Compass by clicking no. However, it is great to read before diving too far into compass.

      Mindscape will now setup some needed items to work with SASS. You'll notice there is a "sass" folder that has several .scss files, you'll also notice a stylesheets folder and lastly, in the root you will see a config.rb file.

      The SASS folder is where all of your SASS files go, they will have the extension .scss, which is for SASS w/ Compass. Te stylesheets folder is where the rendered or generated CSS files will end up. You can change this by changing the variables in the config.rb file.

      Note the config.rb file is written in ruby, which has some largely different syntaxes than many other languages. You don't have a terminating semi-colon, and # precedes a comment line.

    4. Let's setup an action and view so we have some HTML to work with. Edit the Controllers/HomeController.cs file, add this code to the end of the class:

              public ActionResult SassTest()
              {
                  return View();
              }
      

      Right click inside the function above and choose Add View to create a SassTest.cshtml, uncheck the box for "Use a layout page". We will create our own layout in this page to start getting the fundamentals of working with SASS.

      Edit the Views/Home/SassTest.cshtml file and replace the code in it with the below code:

      @{
          Layout = null;
      }
      
      <meta name="viewport" content="width=device-width" />
      <title>SassTest</title>
      <link href="~/stylesheets/screen.css" rel="stylesheet" />
      <header>
          <h1>Testing Sassiness</h1>
      </header><nav>
          <ul>
              <li><a href="#">Home</a></li>
              <li><a href="#">Contact</a></li>
              <li><a href="#">About</a></li>
          </ul>
      </nav>
      <div>
          <h2>Here we go!</h2>
          <div class="tbl">
              <div>
                  <div class="item-15"> </div>
                  <div class="item-20">Language</div>
                  <div class="item-30">Pros</div>
                  <div class="item-30">Cons</div>
              </div>
              <div>
                  <div class="item-15">CSS</div>
                  <div class="item-20">Cascading Style Sheets</div>
                  <div class="item-30">Everyone can read it</div>
                  <div class="item-30">No variables, looping, or branching.</div>
              </div>
              <div>
                  <div class="item-15">LESS</div>
                  <div class="item-20">Less</div>
                  <div class="item-30">
                      <ul>
                          <li>Uses JS to build, so easier installation.</li>
                          <li>Better error notifications with line numbers.</li>
                      </ul>
                  </div>
                  <div class="item-30">
                      <ul>
                          <li>Extensions are provided by a lot of developers, and becomes a hunt and peck to find what you need.</li>
                          <li>Does not allow you to extend definitions.</li>
                          <li>Mathematical operators with different measurement units can cause problems.</li>
                      </ul>
                  </div>
              </div>
              <div>
                  <div class="item-15 lookie">SCSS</div>
                  <div class="item-20">Sass with Compass</div>
                  <div class="item-30">
                      <ul>
                          <li>Extensions are contained in compass.</li>
                          <li>Allows you to "extend" mixins (functions)</li>
                          <li>Will throw an error if try to perform a mathematical operation on % vs px.</li>
                      </ul>
                  </div>
                  <div class="item-30">
                      <ul>
                          <li>Harder to install as you need ruby, unless you use IDE Extensions.</li>
                          <li>Error notifications can often be vague.</li>
                      </ul>
                  </div>
              </div>
          </div>
      </div>
      <footer>
          <p>Copyright ©@DateTime.Today.Year</p>
      </footer>
      
      Sass Test with Reset

      Build the project with Ctrl+Shift+B which will cue Mindscape Web Workbench to ensure the CSS files are built from the .scss, then when you run the site and view the /Home/SassTest page, it should look like the image shown here. You'll notice that all of the margins, paddings, and font-sizes have been normalized. This is due to a built in compass call to a reset document. We will explore that as we dive into the .scss file.

  2. SASS Basics

    • screen.scss-

      Open up the file /sass/screen.scss and let's look at code there. The file starts with the following code in it:

      /* Welcome to Compass.
       * In this file you should write your main styles. (or centralize your imports)
       * Import this file using the following HTML or equivalent:
       *  */
      
      @import "compass/reset";
      
      

      This seems very normal and nothing major or different from CSS. Even the import command is very "CSS". However, this is actually calling a compass mixin that automatically renders some reset CSS code. If you open up the /stylesheets/screen.css you will see about 70 lines of CSS. We got this for free with the compass reset mixin.

    • Comments-

      In a .scss file you have the ability to use both multiline comments with the usual /* comment */ and we also get a singleline comment by preceeding a comment with // similar to C# and JavaScript.

      Add the following line into the screen.scss file:

      //you can use single line comments in sass
      

      Now, rebuild the project and view the screen.css file. You will not notice any difference at all. The single line comments do not get rendered into the CSS file.

    • Variables-

      Variables are not type safe. To declare/assign/reassign a variable you use: $variablename: value; This will create the variable with the value if it doesn't exist and assign it a value, or if the variable already exists it will reassign the value. If you want the value to only be assigned if the variable has NOT been created you can add: !default After the value but before the semicolon. This can be VERY confusing, so let's start here with an example.

      Add the following code to the end of the screen.scss file:

      /*** VARIABLES ***/
      /*
      To create variables in SASS use a $ to declare and : to assign
      If you only want to assign a value if it has not been previous assigned use
      $variable:value !default;
      */
      
      $mainColor: red;
      $bgColor: #fd4a5d;
      $borderColor: green;
      $borderColor: yellow !default;/*will not override green*/
      $fontColor: blue;
      

      You can use variables in your CSS by calling their name. Let's explore using a variable in the scss file. Add the below code to the end of the file:

      header {
      	background-color: $bgColor;
      	color: white;
      	border: 1px solid $borderColor;
      	text-align: center;
      }
      

      Build the project and reload the page. You'll see the header change and the background color will be red, font color white, and the border color will be green. You'll also notice that while singleline comments did not get rendered into the CSS file, multiline comments do.

    • Nesting Selectors-

      SASS allows you to nest selectors. Most CSS pre-processors have this function. The idea is to make the selectors easier to write and hopefully easier to read. Modify the header selector to look like the following:

      header {
      	background-color: $bgColor;
      	color: white;
      	border: 1px solid $borderColor;
      	text-align: center;
      	/*you can nest selectors*/
      	h1 {
      		/* this will render as: 
      			header h1 */
      		color: $fontColor;
      		font-size: 2em;
      	}
      }//end header
      
      

      Build the project and refresh the page, you'll see the header increase in size and turn blue. If you check the screen.css file you'll see that it rendered a header { } selector and a header h1 { } selector. Let's explore this a bit farther. Add the following CSS to the end of the screen.scss file.

      nav 
      {
      	margin: 2em 0;
      	> ul {
      		text-align: center;
      		> li {
      			display: inline-block;
      			margin: 0 2em;
      			padding: .25em;
      			background-color: $bgColor;
      			border: {
      				radius: .5em;
      				width: 2px;
      				style: dotted;
      				color: $borderColor;
      			}
      		}
      	}
      }
      
      
      Sass Test with Nav

      Build and refresh the page. It should look like this image. If you look at the screen.css you can see how the nested selectors are being processed to render the CSS. You can also nest properties with any dashed property. For example the border-radius, border-width, border-style, and border-color. To do that you add the first part of the CSS property with a : and then curly brackets with the second part of the property name and the value for each one.

      I haven't found the nested properties to be very useful yet, but it is interesting to see how it works. The only downside to all of these nested selectors and properties is the abundant closing curly brackets. Which is typically where the single line comments come in handy. So you could change nav code to the following:

      nav 
      {
      	margin: 2em 0;
      	> ul {
      		text-align: center;
      		> li {
      			display: inline-block;
      			margin: 0 2em;
      			padding: .25em;
      			background-color: $bgColor;
      			border: {
      				radius: .5em;
      				width: 2px;
      				style: dotted;
      				color: $borderColor;
      			}
      		}//end > li
      	}//end > ul
      }//end nav
      
      

      You can also nest selectors with pseudo class selectors using an & symbol to concatenate the selector, or even to build more specific selectors. Below I have code written to build a selector for: div.tbl > div:first-child and div.tbl > div:last-child

      Add the below code to the end of the screen.scss file

      div.tbl {
      	width: 90%;
      	margin: 0 auto;
      	min-width: 300px;
      	> div {
      			border: 1px solid black;
      		&:first-child {
      			border-bottom: 0;
      
      		}//end > div:first-child
      		&:last-child {
      			border-top: 0;
      		}//end > div:last-child
      		> div {
      			display: inline-block;
      			padding: 2px;
      			vertical-align: top;
      
      		}//end > div > div
      	}//end > div
      }//end div.tbl
      
      

      Build the project and refresh the page. We still need some code for the div's width, but that will come soon! :)

    • Mixins-

      Mixins are a great way to reuse sections of CSS. For example stacking several effects together that you can reuse in multiple places. Scroll up in the screen.scss file and add the following code after the section for the variables:

      /****** MIXINS *******/
      @mixin awesome-effect {
      	color: $mainColor;
      	/* can nest properties */
      	font: {
      		family: arial;
      		size: 1.2em;
      	}
      }//end awesome-effect
      
      @mixin boxsizing {
      	-webkit-box-sizing: border-box;
      	-moz-box-sizing: border-box;
      	box-sizing: border-box;
      }//end boxsizing
      
      

      The mixins above can be included anywhere in our CSS to place those effects in that selector. You include this into the scss by using:

      @include MIXINNAME;

      Change the div.tbl code and add the @include awesome-effect; and @include boxsizing; where I did in the below example:

      div.tbl {
      	width: 90%;
      	margin: 0 auto;
      	min-width: 300px;
      	> div {
      			border: 1px solid black;
      		&:first-child {
      			border-bottom: 0;
      			@include awesome-effect;//reusability of properties
      		}//end > div:first-child
      		&:last-child {
      			border-top: 0;
      		}//end > div:last-child
      		> div {
      			display: inline-block;
      			padding: 2px;
      			vertical-align: top;
      			@include boxsizing;
      
      		}//end > div > div
      	}//end > div
      }//end div.tbl
      
      
      Sass Test with Nesting

      Build the project and refresh the page, you'll now see the effect for the first row of the div.tbl which starts to show some of the strength of a mixin. However, you can use them to a much greater effect. If you think of a Mixin as more of a "method/function" then it won't seem so odd to start adding parameters to them. As illustrated above mixins are great for those pesky browser prefixes and we can use them to work with variable values as well.. Scroll up to the "mixin" section and add the following code after the boxsizing mixin:

      @mixin columns($nbr) {
      	-webkit-column-count:$nbr;
      	-moz-column-count:$nbr;
      	column-count:$nbr;
      }
      
      

      After the mixin name we have a set of parens with parameters. Since this is a type not safe language, we do not need to specify the data type for the parameter. This parameter variable can be used for the properties within. To use this in our sass we use code similarly to the other mixins, with the exception that we add parens and specify the values for the variables. Modify the div.tbl code to add the @include columns(2); for the nested ul:

      div.tbl {
      	width: 90%;
      	margin: 0 auto;
      	min-width: 300px;
      	> div {
      			border: 1px solid black;
      		&:first-child {
      			border-bottom: 0;
      			@include awesome-effect;//reusability of properties
      		}//end > div:first-child
      		&:last-child {
      			border-top: 0;
      		}//end > div:last-child
      		> div {
      			display: inline-block;
      			padding: 2px;
      			vertical-align: top;
      			@include boxsizing;
      			ul {
      				@include columns(2);//reuse with variables
      			}//end > div > div ul
      		}//end > div > div
      	}//end > div
      }//end div.tbl
      
      

      Build the project and refresh the page. You'll see the nested uls are using the css3 columns. Using mixins for browser prefixes is such a common use that this is where compass typically comes into play. Compass is a library of prewritten mixins that you can pull in. But that is for another tutorial..

    • Media Queries-

      Using the ability to nest selectors is pretty handy, but it really steps up when you start talking about media queries. We can nest @media inside of a selector and the css will be built with a media query for those rules for that specific selector. Change the header selector on line 45ish to the following code:

      header {
      	background-color: $bgColor;
      	color: white;
      	border: 1px solid $borderColor;
      	text-align: center;
      	@media screen and (max-width: 600px ) {
      		background-color: peachpuff;
      	}
      	/*you can nest selectors*/
      	h1 {
      		/* this will render as: 
      			header h1 */
      		color: $fontColor;
      		font-size: 2em;
      	}
      }//end header
      
      

      Build the project and refresh the page. As you resize the browser you'll see the header change colors. If you check out the screen.css file you'll see the following rendered CSS:

      /* line 45, ../sass/sasstest.scss */
      header {
        background-color: #fd4a5d;
        color: white;
        border: 1px solid green;
        text-align: center;
        /*you can nest selectors*/
      }
      @media screen and (max-width: 600px) {
        /* line 45, ../sass/sasstest.scss */
        header {
          background-color: peachpuff;
        }
      }
      /* line 54, ../sass/sasstest.scss */
      header h1 {
        /* this will render as: 
        	header h1 */
        color: blue;
        font-size: 2em;
      }
      

      This ability allows you to add your media queries where you need them and let the CSS do all the work. You can even go a step farther by creating variables for the width page breaks for true reusability.

    • Inheritance-

      Another useful ability of sass is extend. This gives us a form of "inheritance" which lets us share CSS properties and nested selectors. Even more than a mixin. Add the following code to the end of the screen.scss file:

      /*Extend allows you to inherit properties from other selectors. This can get much more complex and
      the implementations go much farther than what I have here, but this is a quick intro. */
      .lookie {
      	background-color: $bgColor;
      	color: #fff;
      }
      
      footer {
      	@extend .lookie;
      	font-size: .8em;
      	text-align: center;
      	margin: 3em 0;
      }
      
      

      Build the project and refresh the page. In the html inside the div.tbl the SCSS has a class of lookie. The above code set the pinkish color for the background with a white font. The same effects are applied to the footer. If you look at the generated screen.css you'll see that the CSS rendered .lookie, footer

      This is just the top of the iceberg on how you can use the @extend ability with sass. It goes even farther by cascading selectors. If you wrote some CSS for @extend footer; It would also be adding to .lookie!! There is also the ability to write extend only selectors using a % symbol. But hopefully this small intro to "extend" will encourage you to dig deeper.. however, I think it's time to talk about looping in sass!

    • Looping-

      So the looping syntax can be very odd... so let's start with an example of code, see the CSS and then disect the sass code. So add the following code to the end of the screen.scss file:

      /*** LOOPING ***/
      $loopClass: item;
      $loopvalue : 5;
      $endloop : 100;
      
      @while $loopvalue < $endloop {
        .#{$loopClass}-#{$loopvalue} { width: 1% * $loopvalue; }
        $loopvalue: $loopvalue + 5;
      }
      //when you enclose a variable inside of #{} the compiler will
      //place that variable literally in that location. So we end up with 
      //.item-5 for the first loop, .item-10 for the second, etc
      //don't place the #{} inside of a multiline comment as you will get an error!
      
      
      Sass Test with Final

      Build the project and refresh the page. The page should look like the screenshot. If you open the screen.css file and view the rendered CSS you'll see a series of classes built from .item-5 to .item-95 with a corresponding width set for each.

      Taking the typical basics of looping this is just written as:

      @while CONDITION { CODE-TO-RUN UPDATE-CONDITION-VARIABLE }

      The pain in the butt part of this is to print a variable in a selector you have to use #{variablename} which you should not do inside of multiline comment as it will cause a sass render error. The other trick is the math portion. This took some fiddling and you have to be careful when it comes to working with math and sass variables. If you try to take 10px * 10% you will get an error! So when would you use the code above? Not sure, the above creates a div table pattern that I have been toying with, but regardless it is the only way I've found to loop at increments other than 1.

      Here is an example with a For loop. I didn't add any html to use this CSS but you can add this to the screen.scss file and see the rendered CSS to view how this works. In short, here is a way to create your own grid system with sass. Add the following code to the end of the screen.scss file:

      $className: grid;
      $gridNumber: 12;
      $gridMax: 100%;
      
      @for $i from 1 through $gridNumber
      {
      	.#{$className}-#{$i}
      	{
      		width: $gridMax / ($gridNumber / $i);
      	}
      }
      
      

      If you check the rendered CSS you can see the result. The cool thing about this loop is you can change the variables and have this render px based grids if you changed $gridMax to 960px, or an 8 grid system by changing the $gridNumber to 8, heck even rename the classes to whatever you want by changing the $className variable!

      Here is one more example using a "foreach" statement on an array. This one seems iffy on how you would use it, but it's worth checking out. Add the following code to the end of the screen.scss file:

      $names : 'bob' 'jack' 'jim' 'george';
      //also works without ''
      
      @each $name in $names {
      	.#{$name} {
      		background-image: url('images/#{$name}.jpg');
      	}
      }
      

      Build the project and then check out the rendered CSS. This foreach statement creates a class for each name with a corresponding background-image. I did find a use for the @each statement in a recent project by having it loop through a list of CSS properties and create CSS animations for each.

  3. Summary

    The possibilities with SASS are endless! Just the simple fact that I can take a CSS file and paste the code right inside the scss file and go on about my day without even needing to use any of the cool sass features means that I can implement sass at my leisure. I don't have to rewrite anything that I don't want to. But what I do rewrite, or build in sass becomes easier to expand on, extend, loop through and reuse. Hopefully, this tutorial has given you a glimpse into the benefits of working with sass or any CSS preprocessor. LESS is another preprocessor that has picked up a lot of support as well. There are some pros and cons to both. As I go through more and more front-end cutting edge tutorials I find almost all of them using SASS. So that's why I went that direction. The only annoying part of working with SASS is needed to compile between changes.

    Please feel free to leave a comment below and let me know what you think!

quonahquee@bestmailonline.com

Comment

This condition is pretty limited to the reproductive system and may have several causes like a results of injury or abnormal blood circulation inside testicles. Use these circumspectly however, since they may lower blood sugar levels, that's an unhealthy effect that face men whose glucose levels are properly balanced.

You must be logged in to comment.

You must be logged in to comment.