Using Sass - Exercise

Contact Us or call 1-877-932-8228
Using Sass - Exercise

Using Sass

Duration: 20 to 30 minutes.

In this exercise, you will download, install, and use Sass to write some simple CSS.

  1. If needed, install Ruby on your computer; RubyInstaller is your best bet if running Windows.
  2. If you haven't yet, install the Sass Ruby gem: type gem install sass (sudo gem install sass and type admin password, if prompted, on a Mac) from the command prompt.
  3. From a command prompt, navigate to the directory ClassFiles/CSSBestPractices/Exercises/.
  4. Type the following command from the command prompt and hit enter: sass --watch style.scss:style.css. This tells Sass to watch file style.scss for changes and, for each change, to compile the results of style.scss into style.css. Note that:
    • Provided that you don't close the command-prompt window, Sass will continue watching for changes, compiling CSS from your Sass code each time you make a change.
    • Because the exercise file style.scss is unfinished (waiting for you to write some code), the compilation will fail until you fill in the missing code.
    • index.html references, through a standard link tag, style.css to get its styles - index.html doesn't know anything about our Sass file style.scss!
  5. Add values for the five Sass variables at the top of style.scss, values like #000, #F00, etc. Note that style rules below reference these variables' values.
  6. In the @for loop, use darken($bg_box_start, $i * 5) for the background-color style rule and lighten($color_box_start, $i * 25) for the color rule. Experiment with different starting colors (from the variables at top) and values for the second parameter ($i * 10 instead of $i * 5, say) to see how these changes affect the page.

Solution:

CssBestPractices/Solutions/style.scss
$bg_body: #CCC;
$bg_main: #FFF;
$bg_box_start: #F00;
$color_box_start: #000;
$border_color: #000;
$number_of_items: 4;

* {
	padding: 0;
	margin: 0;
}

body {
	background-color: $bg_body;
}

#main {
	width: 60%;
	padding: 2% 5%;
	margin: 20px auto;
	background-color: $bg_main;
}

h1 {
	margin-bottom:20px;
}

#main div {
	float: left;
	width: 41%;
	margin: 0 5% 20px 0;
	border: 1px solid $border_color;
	padding: 1%;
}

@for $i from 1 through $number-of-items {
	#main div:nth-of-type(#{$i}) {
		background-color: darken($bg_box_start, $i * 5);
		color: lighten($color_box_start, $i * 25);
	}
}

footer {
	clear:both;
}
Next