Summary: SASS brings common programming ideas and applies them to CSS. This makes CSS much easier and quicker to work with, and allows you create CSS dynamically based off of variables.
Setup: The thing about Rails and SASS is that it's there by default! All you need to do is change the .css file to a .scss file. Easy peasy!
Variables are defined with a $ sign and can be used across your CSS:
$color-one: #4bc9ab;
$color-two: complement($color-one);
$color-three: rgb(183, 24, 196);
$div-radius: 10px;
$text-size: 20px;
Mix-ins allow you to define code to be repeated and pass values through it:
@mixin btn($bgcolor, $radius, $padding){
background-color: complement($bgcolor);
padding: $padding ($padding * 2);
border-radius: $radius;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border: none;
color: white;
&:hover {
background-color: darken(complement($bgcolor), 10);
}
}
And all you need to type to call that later is:
button {
@include btn($color-one, 10px, 15px);
}
You can perform functions on colors and values:
background-color: darken(complement(#006666), 30);
becomes:
background-color: #330000;
You can nest your CSS instead of defining each piece separately:
div {
h1 {
color: lighten(#ff6666, 20);
}
h2 {
color: adjust-hue(#ff6666, 70deg);
}
a {
color: mix(#ff6666, #807333);
&:hover {
color: fade_out( mix(#ff6666, #807333) , 0.7 );
}
}
.grey {
background-color: grayscale(#ff6666);
}
}
becomes:
div h1 {
color: #ffcccc;
}
div h2 {
color: #e6ff66;
}
div a {
color: #c06d4d;
}
div a:hover {
color: rgba(192, 109, 77, 0.3);
}
div .grey {
background-color: #b3b3b3;
}
(with each piece having the div defined)
Instead of defining each individual value, you can perform math on a base value and set realtionships:
$text-size: 20px;
.text-example {
font-size: $text-size;
.big {
font-size: $text-size * 3;
}
.small {
font-size: $text-size / 2;
}
}
becomes:
.text-example {
font-size: 20px;
}
.text-example .big {
font-size: 60px;
}
.text-example .small {
font-size: 10px;
}
All of this allows you to have much more DRY code:
.one {
@include cool-div($color-one, $div-radius);
}
.two {
@include cool-div($color-two, $div-radius);
}
.three {
@include cool-div($color-three, $div-radius);
}
Can define three completely different styles.
Example index.html.erb file