10Calculating a Layout

Sass allows you to do calculations on the fly and in your document: you can easily type width: 12px * 0.5; in your code!

OK, OK—we admit that’s not terribly useful. But it is once we throw variables into the mix. Once we’ve defined a variable, Sass allows us to perform basic operations on that variable using standard operators for adding, subtracting, multiplying, and dividing (+, -, *, and /). The operators will be familiar to anyone who has done any amount of programming before.

We could say something like width: $page_width * 0.1 as a way to avoid hard-coding pixel values. When the CSS is compiled, this will be precalculated and will print out an exact width in pixels.

We can now do previously laborious tasks like calculating and maintaining proportions throughout a layout.

For example, we can define the width of the content area of the page as 500px. Then we can base the width of the sidebar as a proportion of the total width—say 0.2. If we wanted to change the size of the content area, the sidebar can automatically resize itself to fit. All it takes is variables plus some operator know-how.

A quick note about units here. If we define $page_width as 10em and we multiply it by two, the resulting value will keep the em unit. The same goes if it were px. If you mix units, Sass will try to make them work, but if they are incompatible, Sass will display an error. For instance, you can’t multiply a px value by a em value. It just doesn’t make sense.

What To Do...
  • Add, subtract, multiply, or divide using the standard operators.
    basics/layout_calc.scss
     
    $​width​: 10px;
     
    $​double_width​: $​width​ ​*​ 2;
     
    $​half_width​: $​width​ / 2;
     
    $​width_plus_2​: $​width​ + 2;
     
    $​width_minus_2​: $​width​ - 2;
  • Use calculations inline.
    basics/calc_inline.scss
     
    $​width​: 500px;
     
    $​sidebar_percent​: 0.2;
     
    #page {
     
    width: $width;
     
    #sidebar {
     
    width: $width * $sidebar_percent; }
     
    #content {
     
    width: $width * (1 - $sidebar_percent); } }

    This compiles to:

     
    #page {
     
    width: 500px; }
     
    #page #sidebar {
     
    width: 100px; }
     
    #page #content {
     
    width: 400px; }

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset