Beruflich Dokumente
Kultur Dokumente
receptive
applications. This book will help you develop faster and reduce the maintenance time for your web
development projects by using Sass and Compass. You will learn how to use CSS frameworks such as
Bootstrap and Foundation and understand how to use other libraries of pre-built mixins. You will also learn
about setting up a development environment with Grunt.
This book guides you through all the concepts and gives you practical examples for fuller understanding.
maintainable CSS
Integrate Sass in your own projects
Reuse your code to prevent code
duplications
Write reusable and portable CSS code
Make use of pre-built and established
with Grunt
and problems
problems efficiently
real-world problems
P U B L I S H I N G
Bass Jobsen
$ 49.99 US
31.99 UK
P U B L I S H I N G
Fr
ee
Sa
pl
e
Bass Jobsen
Preface
Sass (Syntactically Awesome Stylesheets) is a CSS extension language or preprocessor, which
means that Sass or SCSS code compiles into static CSS code. Sass changes the way you write
and maintain your CSS code; the final CSS code will be the same, although better organized in
many situations.
Since the introduction of CSS3 in 2012, the role of CSS in modern web development has
become more and more important. Nowadays, CSS3 is not only used to style your HTML
documents, but it also plays an important role in the responsibility of your designs too. Last,
but not least, CSS3 extends CSS with features such as animations and transitions.
Writing correct functional CSS code will be the first thing; keeping this code readable, working
on all major browsers, and maintainable will be the second. CSS files grow and become
untidy in the development and maintenance processes. CSS doesn't have the ability to modify
existing values or reuse common styles. Also, doing the math or defining variables is not
possible in CSS. This is where the Sass language comes into the frame.
The Sass language enables you to write your CSS code DRY (Do not Repeat Yourself) because
it extends the CSS syntax with variables, mixins, functions, and many other techniques. Sass
makes the CSS language is more maintainable, themeable, and extendable.
Also, others know the power of Sass. Projects such as Bootstrap 4 and the Foundation are
built with Sass. These projects create clear and extendable Frameworks with Sass. Bootstrap
chose Sass because of the increasingly large community of Sass developers. You can't ignore
these proofs. Stop writing cumbersome CSS with bugs and browser defects and learn Sass by
reading this book.
In this book, you will learn to write, compile, and understand the Sass language. It helps with
faster and more cost-effective web development. You will get practical tips to integrate Sass in
your current and new projects. After reading this book, you will write clear and readable CSS3
with Sass. Instead of spending your time debugging your complex CSS code for a specific
device or browser, you could pay more attention to your real design tasks.
Preface
Your clients will be happy with your advanced and stable designs. Development and
maintenance time, and therefore costs, shall decrease.
Sass is available for use and modification under the MIT License. You can use Sass free
of charge.
Preface
Chapter 11, Foundation and Sass, explores Foundation for Sites 6. Foundation is a responsive
frontend framework built with Sass.
Chapter 12, Bootstrap and Sass, explains details about Bootstrap 4. Bootstrap 4 uses Sass
now. Learn how to develop mobile first and responsive projects with Bootstrap and Sass.
Chapter 13, Meeting the Bourbon Family, explains about Bourbon, which is a simple and
lightweight mixin library for Sass; it helps you write CSS faster and easier without the need
of using vendor prefixes.
Chapter 14, Ruby on Rails and Sass, builds web applications with Ruby on Rails (RoR) and
Sass. Get to grips with sass-rails to compile the CSS code for your RoR apps.
Chapter 15, Building Mobile Apps, explains that the look and feel of mobile apps may
differ from that of other web applications. Get introduced to Frameworks for mobile app
development with Sass. Build mobile apps with Foundation for Apps and Ionic.
Chapter 16, Setting up a Build Chain with Grunt, gives introduction to Grunt, a build tool for
JavaScript projects. Learn how to create tasks to automatically compile, compress, and prefix
your CSS code.
Building Layouts
with Sass
In this chapter, you will learn the following:
Introduction
In the recipes in this chapter, you will learn how to create a layout for your website or web
application with Sass. The grid forms the basics of the layout. Grids help web designers
and developers to work together and make deploying responsive layouts easier.
203
204
Chapter 9
Getting ready
In this recipe, you will use Normalize.css as an alternative for other CSS Resets. You can
download Normalize.css at https://necolas.github.io/normalize.css/. After
downloading the file you can compile your code with the Ruby Sass compiler. The Installing
Compass recipe of Chapter 1, Getting Started with Sass describes how to install Compass
for command line usage on your system.
How to do it...
Perform the the following step to use Normalize.css as an alternative for other CSS Resets in
your Sass code:
1. Download the normalize.css file at https://necolas.github.io/
normalize.css/.
2. Rename the normalize.css to _normalize.scss and then create the file and
directory structure like that shown in the following figure:
3. Your main.scss can now import the _normalize.scss partial file by declaring
the following line of code:
@import 'base/normalize';
4. As you will see now, when you compile your project by running the command like that
shown in the following code, the compiled CSS code will start with the CSS code from
normalize.css:
sass main.scss
205
How it works...
CSS resets the overwrite of the default styling rules of the browser and creates a starting point
for styling. This starting point looks and acts the same on all (or most) browsers. In this book,
Normalize.css v3.0.2 is used. Normalize.css is a modern, HTML5-ready alternative
to CSS Resets. It lets browsers render all elements more consistently and makes them adhere
to modern standards.
In this recipe, you had to rename the original CSS file. You should prepend an underscore
to the file name and change the file extension to make it a Sass partial file. The preceding
prevents Sass from compiling the file into CSS. Read more about partials in the Working
with partials recipe of Chapter 1, Getting Started with Sass. Also notice that changing the
file extension from .css to .scss will prevent Sass from creating a regular CSS @import
declaration instead of importing and processing the file, as explained in the Importing and
organizing your files recipe of this chapter. You should always import the reset code at the
beginning or top of your style rules.
Bootstrap 4, as described in Chapter 12, Bootstrap and Sass, uses an extended version of
Normalize.css called Reboot.
There's more...
When you start a project, you should also think about the CSS Reset that you will have to use.
Writing a CSS Reset yourself seems like reinventing the wheel again. On the other hand, using
a random CSS Reset code without any research may cause unwanted effects or unnecessary
process time for your project. Your choice should depend on using HTML5 or not, the browsers
that you will have to support, and so on. At http://www.cssreset.com/, you can find and
download the most popular CSS Resets, including Normalize.css. To make a motivated
choice, you can read the Which CSS Reset Should I Use? section on that website, too.
Download the CSS file (with the .css extension) of the CSS Reset of your choice and save this
file into your working directory. Rename it as shown in this recipe. You can use the Ruby Sass
compiler to see how the CSS Reset compiles into your final CSS code.
The oldest and most famous browser reset is Eric Meyer's CSS Reset. When you use Compass
as described in Chapter 6, Using Compass, you can directly apply Meyer's CSS Reset by using
the Compass Reset module. The module applies the global reset to your stylesheet by simply
importing it.
Use Meyer's CSS Reset with compass by declaring the following @import statement at the
beginning of your code:
@import 'compass/reset';
206
Chapter 9
See also
Read more about Eric Meyer's CSS Reset at http://meyerweb.com/eric/tools/css/
reset/.
Getting ready
In this recipe, you only will compile a single Sass template into CSS code to demonstrate the
use of the @import directive. You can compile this template by using the Ruby Sass compiler.
Read the Installing Sass for command line usage recipe of Chapter 1, Getting Started with
Sass, to find out how to install Ruby Sass.
How to do it...
The following steps will learn you how to import files and organize your files:
1. Create a Sass template called imports.scss. The imports.scss file should
contain the following lines of SCSS code:
@import
@import
@import
@import
'file.css';
'file' screen;
'http://sass-lang.com/file.scss';
url(file.scss);
2. Then run the following command in your console to compile it into CSS code:
sass imports.scss
3. Finally, you will find that the SCSS code from Step 1 compiles into static CSS code like
that shown in the following:
@import url(file.css);
@import "file" screen;
@import "http://sass-lang.com/file.scss";
@import url(file.scss);
207
How it works...
The syntax of the @import directive in Sass is similar to the @import at-rule in CSS. So Sass
should only process Sass templates and leave other @import at-rules intact. When you import
a Sass template, you do not explicitly have to set the file extension; the compiler automatically
searches for files with the .scss and .sass extension and processes these files.
As you can see when evaluating the compiled CSS code in Step 3, all other declarations
compile into a regular CSS @import at-rule.
The @import 'file.css'; declaration will not be processed due to the .css extension.
The second declaration contains the screen media query. At compile time, there is no
context to evaluate the media query so this declaration also compiles into a CSS @import
at-rule. Also, file names that are in the url() form, or start with http://, will compile into
CSS @import at-rules.
Remember that Sass will ignore files that begin with underscores until you specifically import
them. These files are called partials. In this book, the so-called 7-1 pattern has been used to
organize the Sass templates. Note that you may not include a partial and a non-partial with
the same file name in the same directory. You can read more about partials in the 7-1 pattern
in the Working with partials recipe of Chapter 1, Getting Started with Sass.
There's more
Although you mostly use the @import directives at the beginning of your style document,
Sass also allows you to nest a Sass with the @import directive inside of a style rule.
When your _nested.scss partial file contains the SCSS like that shown as follows:
p {
color: red
}
208
Chapter 9
See also
Read more about the CSS @import at-rule, which allows you to import style rules
from other stylesheets, at https://developer.mozilla.org/en/docs/Web/
CSS/@import.
You can read more about the 7-1 pattern developed by Hugo Giraudel at
http://sass-guidelin.es/#the-7-1-pattern.
Read why you should not use Sprockets directives in Asset Pipeline to combine your
Sass files at http://blog.pivotal.io/labs/labs/structure-your-sassfiles-with-import.
Matt Stauffer wrote a quick blog post about Nesting Sass @imports, with BEM. You
can find Stauffer's post at https://mattstauffer.co/blog/nesting-sassimports-with-bem.
The Sass globbing plugin allows you to import many Sass or SCSS files in a
single import statement. You can find this plugin at https://github.com/
chriseppstein/sass-globbing.
And finally the Sass CSS Importer plugin, which enables you to import a CSS file
into Sass, can be found at https://github.com/chriseppstein/sass-cssimporter.
209
Getting ready
The code used in this recipe is based on the CSS3 Flexible box module, using the same
naming conventions as Bootstrap. Read more about Bootstrap in Chapter 12, Bootstrap
and Sass. Notice that Bootstrap 4 also has opt-in flexbox support.
Though it will be interesting to inspect the compiled code, the best way to test the grid you
will construct in this recipe will be to use it in your browser. Notice that the code in this recipe
uses the official W3C syntax for flexboxes, so you should use a browser that supports this
syntax. You can find out which browsers support the Flexible box layout at http://caniuse.
com/#feat=flexbox.
Also, the box-sizing property, as described in the There's more... section, should
be supported by your browser. In the How it works... section of this recipe, you can read
how to add support for older browsers, too.
If you are not familiar with the CSS Flexible box module already, it's
strongly recommended that you read more about it before you start this
recipe. An excellent article titled A Complete Guide to Flexbox can be
found at http://css-tricks.com/snippets/css/a-guideto-flexbox/.
Of course, you will have to compile the Sass code of the recipe. Read Chapter 1, Getting
Started with Sass to find out how to install Sass on your system. Also read the Using vendor
prefixes recipe of Chapter 7, Cross-Browser CSS3 Mixins.
How to do it...
Now, build a flexbox grid yourself by performing the following steps:
1. Firstly, create a Sass file called sass/main.scss and write down the SCSS code
shown here into this file:
@import
@import
@import
@import
'utils/variables';
'base/normalize';
'base/base';
'layout/grid';
The file shown previously contains the CSS Reset as already described in the Using
a CSS Reset recipe of this chapter. In the section of this recipe, you can read about
setting the box-sizing property to make a calculation of widths inside your grids
more easily. The base/_base.scss file only sets the box-sizing property.
210
Chapter 9
2. Create a Sass partial file called utils/_variables.scss and write down the
SCSS code into this file:
// variables;
$half-gutter-width: .5rem !default;
$gutter-compensation: -.5rem !default;
$outer-margin: 2rem !default;
$grid-columns: 12 !default;
$border-color: #ff6347 !default; // tomato
3. Also, create the layout/_grid.scss partial file and write down the SCSS code
for the grid into it:
// mixins
@mixin grid () {
padding-right: $outer-margin;
padding-left: $outer-margin;
}
@mixin row() {
box-sizing: border-box;
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-right: $gutter-compensation;
margin-left: $gutter-compensation;
}
@mixin make-columns($grid-columns: $grid-columns) {
@for $i from 1 through $grid-columns {
.col-#{$i} {
flex-basis: ((100% / $grid-columns) * $i);
max-width: ((100% / $grid-columns) * $i);
}
}
}
// the grid
.grid {
@include grid();
}
211
4. Now run the following command in your console to compile the SCSS code from Step
3 into CSS code:
sass sass/main.scss main.css
5. Then, create an HTML file named index.html and include the main.css file into it
by adding the following lines of HTML code to the head section:
<link rel="stylesheet" type="text/css" href="main.css" />
6. Now write the following snippet of HTML code into the body of the index.html file to
make the grid visible in your browser:
<div class="grid">
<div class="row">
<div class="col-12"> </div>
</div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6"> </div>
</div>
<div class="row">
<div class="col-4"> </div>
<div class="col-4"> </div>
<div class="col-4"> </div>
</div>
</div>
212
Chapter 9
7.
Finally, load the index.html file in your browser and you will find that it will look as
shown in the following screenshot:
How it works...
You have created separate files for variables, mixins, and even the grid code. As already
mentioned, the code used in this recipe is inspired by the flexbox grid library. The code has
been simplified to keep the recipe clear and understandable.
In this recipe, you will use a @for loop directive as described in the Using the @for directive
recipe of Chapter 8, Advanced Sass Coding, to create the grid classes. In contrast to more
semantic grid systems, such as the grid described in the Building a semantic grid with mixins
recipe of this chapter, the SCSS code in this recipe compiles into 12 grid classes. Some of
these grid classes might never be used for your project. The compiled CSS code contains
more code than possibly needed; on the other hand, you can easily apply the grid for your
designs and reuse the CSS code.
The general properties for the col-* classes are set with the [class^="col-"],
[class*=" col-"] selectors. These attribute selectors reduce the size of the CSS or
make an additional base class unnecessary. Some developers avoid attribute selectors
because they have a negative influence on performance. The partial attribute selector
performance is indeed worse for Microsoft's Internet Explorer web browser. Also note that the
overall performance of the CSS code never depends on a single selector, and calculations
are complex. When optimizing your CSS code, removing unused selectors will have a more
significant effect on performance.
If you resize the browser window when looking at the results of this recipe, you will find that
the flexbox grid already acts in a fluid manner. When the size of the grid changes, the grid
items resize too and the aspect ratios are kept intact. To create a responsive design, you
probably also want to change the size of your grid items depending on the screen size. In the
Creating responsive grids recipe of this chapter, you will learn how to use CSS media queries
to create a responsive grid.
The Sass code in this recipe does not add browser prefixes for properties to support older
browsers. Of course, you can write your own set of mixins to add these vendor prefixes to your
flex-* and box-sizing properties, but a better alternative in this situation seems to use
a mixin library with support for the CSS3 flexbox module. Notice that you can read more about
the box-sizing property of the CSS Box model at the end of this section.
213
There's more
In this section, you will learn how to use the box-sizing property of the CSS Box model.
214
Chapter 9
box-sizing: $boxmodel;
}
$background-color: #000; // black
$border-color: #f00; // red
$font-color: #fff; // white
.container {
&.fit {
@include box-sizing(border-box);
}
> div {
@include box-sizing(inherit);
background-color: $background-color;
border: 5px $border-color solid;
color: $font-color;
float: left;
padding: 10px;
width: 50%;
}
}
The compiled CSS code of the preceding SCSS code can be applied to the following
HTML snippet:
<div class="container">
<div>col 1</div>
<div>col 2</div>
</div>
<div class="container fit">
<div>col 3</div>
<div>col 4</div>
</div>
When you load the preceding code into your browser, it will look like what is shown in the
following screenshot:
215
See also
An online service that prefixes your CSS code can be found at http://prefixr.
com/
You can read an interview with Lea Vera, author of the -prefix-free project, by
Chris Coyier of CSS-tricks.com at http://css-tricks.com/five-questionswith-lea-verou/
The style rules inside the preceding media query will only be applied when the screen's width
(viewport) is equal to or wider than 768 pixels.
Getting ready
In this recipe, you will have to use the code from the Building a grid with grid classes recipe of
this chapter. You also will have to use the command line Ruby Sass compiler. Read Chapter 1,
Getting Started with Sass, to find out how to install Sass on your system.
216
Chapter 9
How to do it...
Perform the following steps to create a responsive grid yourself:
1. Copy the files from the Building a grid with grid classes recipe of this chapter into
your working directory. You should end up with a file and directory structure like
that shown in the following figure:
3. Also, remove the make-columns() mixin call at the end of the sass/layout/_
grid.scss file.
4. Next, create a sass/main.scss file that will contain the following SCSS code:
@import
@import
@import
@import
'utils/variables';
'base/normalize';
'base/base';
'layout/grid';
217
6. In the next code, you will find part of the compiled CSS code that contains the styles
for the columns of the grid. The other styles for the grid, including flexbox properties,
are not shown:
.col-xs-1 {
flex-basis: 25%;
max-width: 25%; }
.col-xs-2 {
flex-basis: 50%;
max-width: 50%; }
.col-xs-3 {
flex-basis: 75%;
max-width: 75%; }
.col-xs-4 {
flex-basis: 100%;
max-width: 100%; }
@media (min-width: 48em) {
.col-sm-1 {
flex-basis: 25%;
max-width: 25%; }
.col-sm-2 {
flex-basis: 50%;
max-width: 50%; }
.col-sm-3 {
flex-basis: 75%;
max-width: 75%; }
.col-sm-4 {
flex-basis: 100%;
max-width: 100%; } }
218
Chapter 9
7.
Now write down the following HTML code into the index.html file:
<div class="grid">
<div class="row">
<div class="col-xs-2 col-sm-3">col-xs-2 col-sm-3</div>
<div class="col-xs-2 col-sm-1">col-xs-2 col-sm-1</div>
</div>
</div>
8. In your browser, the previous code should look like that shown in the following figure:
9. Finally, resize your browser so that the screen width is smaller than 40em (~640
pixel) and you will find that each column gets 50% of the width of the grid now.
How it works...
In this recipe, you created two grids: the xs (extra small) grid with the col-xs-* classes,
and the sm (small) grid with the col-sm-* classes for screen sizes wider than 40 em. Notice
that the breakpoint has been set in em units instead of pixels. The em units let the media
queries appropriately respond to a change in font size, such as when the user magnifies the
page. Modern browsers do not require media queries in (r)em values for correct zooming;
viewports do not depend on font sizes and earlier bugs about the zooming behavior have
already been fixed. Also, Bootstrap 4 defines its breakpoint in pixel values again. Also realize
that pixels provide absolute control and consistent rendering across every browser. Designers
used to think and operate in pixels.
There's more...
To make the code act in a mobile-first manner, the .make.-cols(xs); mixin call is not
wrapped in any media query. You can also use this strategy for other style rules. Start with the
default style rules without media queries and add more or other style rules for wider screen
sizes with media queries, which set the min-width condition. The mobile-first strategy refers
to earlier times when mobile browsers did not support JavaScript or the full range of CSS (or
CSS3) rules. This strategy is still true, and the browser loads the default-style rules first. Other
style rules are loaded and applied if the browser supports them. The mobile-first strategy also
prevents the browser from loading features and style rules that are never used in the situation
where bandwidth and processing power are limited.
219
See also
Getting ready
In this recipe, you will have to use the code from the Building a grid with grid classes and
Creating responsive grids recipes of this chapter. You will use the Ruby Sass compiler as
described in Chapter 1, Getting Started with Sass, to compile your CSS code.
How to do it...
Learn how to set up a semantic grid by performing the step beneath:
1. Leverage the SCSS code from the Building a grid with grid classes and Creating
responsive grids recipes, and edit the sass/layout/_grid.scss file so that
it contains the following SCSS code:
@mixin set-span($col-number) {
flex-basis: ((100% / $grid-columns) * $col-number);
max-width: ((100% / $grid-columns) * $col-number);
}
@mixin grid-item($span, $unit) {
@if $unit == xs {
@include set-span($span);
} @else if $unit == sm {
@media (min-width: $sm-breakpoint) {
@include set-span($span);
}
}
}
220
Chapter 9
2. The SCSS code in the sass/main.scss file should look like that shown in
the following:
@import
@import
@import
@import
'utils/variables';
'base/normalize';
'base/base';
'layout/grid';
article {
@include grid-item(4,xs);
@include grid-item(2,sm);
}
4. Finally, the compiled CSS code should look like that shown in the following:
article {
flex-basis: 100%;
max-width: 100%; }
@media (min-width: 48em) {
article {
flex-basis: 50%;
max-width: 50%; } }
How it works...
The Sass compiler does not group equal media queries; this is why the loop in the Building a
grid with grid classes recipe was called inside a media query, as can be seen in the following
snippet of SCSS code:
@media (min-width: $sm-breakpoint) {
@include make-columns(sm);
}
When each iteration of the loop creates a class that includes the corresponding media query,
the compiled CSS will become inefficient and contain many unnecessary media queries. The
result of the preceding code is that the mixins of the flexbox grid library do not define media
queries. Moreover, the original make-column() mixin always creates a class.
221
Now you can call the set-span() mixin to set the flexbox properties without defining a class.
To solve the media query issue, a grid-item() helper mixin has been created. The griditem() helper mixin sets the required media query based on the $span input parameter
and the already defined $*-breakpoint variables. Notice that media queries are still not
grouped, but the number of media queries will be limited when you have to generate all the
grid classes.
There's more...
Building your grid with responsive mixins instead of CSS classes helps you to write more
semantic HTML code. Also notice that grid items should still be wrapped in a row and a
row, in turn, should have a grid as its parent. The need for these wrappers to set the flexbox
properties will mean you can't build a pure semantic layout.
The semantic.gs grid system enables you to build pure semantic grids. You can read more
about semantic.gs in the Building semantic grids with semantic.gs recipe of this chapter.
See also
A post CSS processor such as CSS MQPacker can pack the same CSS media query
rules into one media query rule. CSS MQPacker can be found at https://github.
com/hail2u/node-css-mqpacker. Also read the Automatically prefixing your
code with Grunt recipe of Chapter 16, Setting up a Build Chain with Grunt to find
out how to integrate postprocessors in your build process using PostCSS.
222
Chapter 9
Getting ready
Read Chapter 1, Getting Started with Sass to find out how to compile your CSS code using
Ruby Sass. You will reuse the code from the Building a grid with grid classes recipe of
this chapter.
How to do it...
You need to perform the following steps to apply the grid on your design:
1. Copy the files of the Building a grid with grid classes recipe of this chapter into your
working directory. Your file and directory structure should look like that shown in the
following figure:
2. Now edit the sass/layout/_grid.scss file. Write down the following SCSS code
at the end of this file:
@mixin make-cols($grid) {
@for $col-number from 1 through $grid-columns {
@include make-column($grid, $col-number);
}
}
@include make-cols(xs);
223
3. The Main Body part in the HTML code in Step 5 contains an unordered list (ul).
This list gets grid classes to lay it out. Use the following SCSS at the end of the sass/
main.scss file to set the colors and other styling elements of the items on the list:
.blocks {
padding: 0;
li {
background-color: $blocks-background-color;
border: 2px solid;
color: $blocks-font-color;
font-size: 3em;
height: 100px;
padding: 10px;
}
}
4. Compile the sass/main.scss file by running the following command in the console:
sass sass/main.scss main.css
5. Finally, create an index.html file and write the following HTML code into it:
<div class="grid">
<header class="row">
<h1 class="col-xs-12">Flexbox Grid System</h1>
</header>
<div class="row">
<!-- Main Body -->
<section class="col-xs-12 col-sm-9">
<ul class="row blocks">
<li class="col-xs-12 col-sm-6 col-md-4">1</li>
<li class="col-xs-12 col-sm-6 col-md-4">2</li>
<li class="col-xs-12 col-sm-6 col-md-4">3</li>
<li class="col-xs-12 col-sm-6 col-md-4">4</li>
<li class="col-xs-12 col-sm-6 col-md-4">5</li>
224
Chapter 9
<li class="col-xs-12
<li class="col-xs-12
<li class="col-xs-12
<li class="col-xs-12
</ul>
</section>
col-sm-6
col-sm-6
col-sm-6
col-sm-6
col-md-4">6</li>
col-md-4">7</li>
col-md-4">8</li>
col-md-4">9</li>
6. Load the index.html file in your browser and you will see what it will look like in
the following screenshot:
Also, resize your browser window to see the effect of the media queries. The previous
figure shows the layout for screens (viewports) between 768 pixels (48em) and 960 pixels
(60em) wide.
225
How it works...
The SCSS code of this recipe with different grids for different screen sizes is defined. For each
grid, there are a set of classes that set the column span for the grid items. The naming of the
grid classes is equal to that in Bootstrap 3. In Chapter 12, Bootstrap and Sass, you can read
about Bootstrap 4; the small grid of Bootstrap 4 starts at a screen width of 544 pixels instead
of 768 pixels.
This recipe also shows you that a grid row can be easily nested. The <ul class="row
blocks"> element defines a nested row. In the small ( sm ), medium ( md ), and large ( lg )
grids, this nested row has a 9 divided by 12 equals 75 percent of the screen width due to
the col-sm-9 class of its parent.
In the Building a semantic grid with mixins recipe of this chapter, you can read how to use
mixins to set the properties of a grid item. Leveraging the mixins from this recipe, which are
not included in the Less code you have downloaded, you could also use the following SCSS
code to style the block structure:
.row.blocks li {
.grid-item(12,xs);
.grid-item(6,sm);
.grid-item(4,md);
}
The compiled CSS of the preceding SCSS code will make the repeated usage of the
col-xs-12 col-sm-6 and col-md-4 classes in the list of blocks unnecessary,
which will help you to keep your HTML clean and readable.
There's more...
As already mentioned, the SCSS code declarations in the recipe only contain the official
and unprefixed W3C syntax for the flexbox properties. You should use the autoprefixer, as
described in the Automatically prefixing your code with Grunt recipe of Chapter 16, Setting
up a Build Chain with Grunt, to prefix your code.
Adding the browser prefixes, as described in the preceding steps, does not add flexbox
support for older browsers, such as Internet Explorer below version 9. For older browsers that
don't support flexbox, you can create a fallback. Tools such as Modernizr can be used to check
for flexbox support. In the Reusing Bootstrap's grid recipe of Chapter 12, Bootstrap and Sass,
you can read how to compile Bootstrap's grid into a single CSS file. Because the flexbox grid
code uses the same naming conventions for grid classes as that of Bootstrap, you could also
consider using Bootstrap's grid as a fallback for Internet Explorer 8. Notice that Bootstrap 4
itself has already got optional flexbox support.
226
Chapter 9
See also
Getting ready
In this recipe, you will integrate this navigation menu in the example layout created in the
Applying the grid on your design recipe of this chapter. Read the preceding recipes mentioned
in this chapter before you start is recommended. Use a flexbox-ready browser to inspect the
results of this recipe. You can check for support for the flexbox module of your browser at
http://caniuse.com/#feat=flexbox. The SCSS is compiled with Ruby Sass on the
command line. Read the Installing Sass for command line usage recipe of Chapter 1,
Getting Started with Sass to find out how to use Ruby Sass.
How to do it...
The following steps will show you how to integrate a vertical navigation menu into the layout
you have created before in the the Applying the grid on your design recipe:
1. Start by copying the files of the Applying the grid on your design recipe of this chapter.
2. Then, create a sass/components/_navigation.scss file and write the following
SCSS code into it:
nav#mainmenu > ul {
list-style: none;
margin: 0;
padding: 0;
background: purple;
display: flex;
flex-direction: column;
@media all and (min-width: $sm-breakpoint) {
justify-content: space-around;
227
5. Open the index.html file you copied from the Applying the grid on your
design recipe. Write the following HTML code between the <header> and <div
class="row"> tags:
<nav id="mainmenu" class="row" role="navigation">
<ul class="col-xs-12">
<li><a href="">Menu item 1</a></li>
<li><a href="">Menu item 2 (long text)</a></li>
<li><a href="">Three</a></li>
</ul>
</nav>
228
Chapter 9
6. Finally, save the modified index .html file and load it into your browser. The result
should look similar to what is shown in the following screenshot:
How it works...
The navigation menu uses the same breakpoints set by the $sm-bsreakpoint and $mdbreakpoint variables in the sass/utils/_variables.scss file as the layout grid. For
small screens, the menu items stack due to the flex-direction: column; declaration
and, for wider screens, the menu becomes horizontal due to the flex-direction: row;
declaration. Finally, for large screens, the menu moves to the right of the page due to the
justify-content: flex-end; declaration.
There's more...
As already mentioned several times in this chapter, the flexbox syntax requires vendor prefixes
for better browser compatibility. Read Chapter 7, Cross-Browser CSS3 Mixins to find out
more about vendor prefixes. Of course, you can also run the autoprefixer, as described in the
Automatically prefixing your code with Grunt recipe of Chapter 16, Setting up a Build Chain with
Grunt, or use Compass; see Chapter 6, Using Compass, to declare your flexbox properties.
See also
You can read more about flexbox in the CSS specifications at http://www.w3.org/
TR/css3-flexbox/
The Compass flexbox module provides prefixing support for the three versions of
flexbox that have been implemented by browsers since 2009. You can find more
about this module at http://compass-style.org/reference/compass/
css3/flexbox/
229
Getting ready
For this recipe, you have to download the latest version of the semantic.gs mixins, which can
be found at https://github.com/tylertate/semantic.gs/zipball/master. After
editing the Sass files with a text editor, you can test the result in your browser. Use the Ruby
Sass compiler as described in Chapter 1, Getting Started with Sass, to compile your CSS code.
How to do it...
In this recipe, you will rebuild the example that is also shown on the home page of the
semantic.gs website. The media queries in the example code are changed so that the
compiled CSS code will follow the mobile-first approach:
1. Download the files of the semantic.gs library from https://github.com/
tylertate/semantic.gs/zipball/master and unzip it in the sass folder
of your project.
2. After unzipping the files, you should end up with a file and directory structure like that
shown in the following:
230
Chapter 9
3. Use your favorite editor to edit the sass/main.scss file, and write down the
following SCSS code into this file:
$column-width: 60;
$gutter-width: 20;
$columns: 12;
$total-width: 100%;
@import 'semantic.gs/stylesheets/scss/grid';
header {
@include column(12);
}
article {
@include column(12);
}
aside {
@include column(12);
}
@media (min-width: 960px) {
article {
@include column(9);
}
aside {
@include column(3);
}
}
4. Compile the sass/main.scss file by running the following command in the console:
sass sass/main.scss main.css
5. Create and edit the index.html file, which should contain the following HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
231
6. Finally, load the index.html file in your browser. You will find that the aside
element float on the right-hand side of the article as expected.
How it works...
The semantic.gs mixins provide you with an easy way to build a responsive grid without
classes, and that is it. It is good to realize that using a grid does not have to break the
semantic structure of your website.
Creating a responsive layout with the semantic.gs mixins is easy and straightforward. You
can set the number of columns with the $columns variable; also, the column width and
the gutter size are set by variables.
You will also notice that the grid had some limitations. In the recipe, the column size of the
compiled CSS is fixed, although the columns stack for screen widths taller than 960 pixels
will be set to 960 (12 x ( $column-width + $gutter-width)). The gutter is set with
the margin property. This issue can be partly solved by setting the $total-width variable to
100%. After that the column widths (and margins) are also calculated as a percentage of the
total available width and the grid becomes fluid.
There's more...
The semantic.gs mixins use the float CSS property to layout the grid columns, just like
Bootstrap, although Bootstrap 4 has got opt-in flexbox support too. Bootstrap, as discussed in
this chapter, builds its grid with div HTML elements and classes. Bootstrap 4 also includes
Sass variables and mixins to quickly generate semantic layouts.
232
Chapter 9
You can download Bootstrap's source files, including the Sass files, at http://
getbootstrap.com/. Notice the following example code uses Bootstrap version 4. After
that, you can import bootstrap's SCSS code into your main.scss project file. Write
down the following SCSS code into the main.scss file:
@import 'scss/variables';
@import 'scss/mixins';
@import 'scss/grid';
$breakpoint: 960px;
// Reset the box-sizing
*,
*:before,
*:after {
box-sizing: border-box;
}
r {
@include make-container();
}
.row {
@include make-row();
}
header {
@include make-col();
@include make-col-span(12);
}
article {
@include make-col();
@include make-col-span(12);
@media (min-width: $breakpoint) {
@include make-col-span(9);
}
}
aside {
@include make-col();
@include make-col-span(12);
@media (min-width: $breakpoint) {
@include make-col-span(3);
}
}
233
See also
Getting ready
Read Chapter 6, Using Compass, to learn more about Compass. Also read the Installing Sass
for command line usage recipe of Chapter 1, Getting Started with Sass. This recipe uses the
SCSS you have used for the Creating grids with semantic.gs recipe.
How to do it...
Learn how to use the Compass Layout Module by performing the following steps:
1. Copy the files from the Creating grids with semantic.gs recipe into your working
directory.
2. Then, edit the sass/main.scss file and make sure it contains the following SCSS
after that:
@import 'semantic.gs/stylesheets/scss/grid';
@import 'compass/layout/grid-background';
234
Chapter 9
$column-width: 60;
$gutter-width: 20;
$columns: 12;
$total-width: 960px;
$grid-background-total-columns: $columns;
$grid-background-column-width: $column-width * 1px;
$grid-background-gutter-width: $gutter-width * 1px;
body {
@include column-grid-background();
}
header {
@include column(12);
}
article {
@include column(12);
}
aside {
@include column(12);
}
@media (min-width: 960px) {
article {
@include column(9);
}
aside {
@include column(3);
}
}
3. Compile the sass/main.scss file by running the following command in the console:
sass --compass sass/main.scss main.css
235
How it works...
The grid images are created by CSS3 gradient images. Read the Using vendor prefixes recipe
of Chapter 7, Cross-Browser CSS3 Mixins, to learn more about CSS3 gradients and Sass. The
code-compiled CSS code generates background images for the body selector. As you can see,
you can use these grid images for testing both horizontal and vertical grids.
There's more...
The Compass Layout Module also contains mixins and functions to build sticky footers and to
style absolutely positioned elements such that they will stretch to fill their positioning parent.
You cannot use this module to build a complete (grid-based) page layout. Earlier versions of
Compass ship with Blueprint CSS. Blueprint does not support the responsive approaches that
are essential to web design nowadays.
Compass removed Blueprint CSS since version 0.13. Compass recommends you to use
Susy to build your grid systems now. You can read more about Susy in Chapter 10, Building
Grid-based Layouts with Susy and Sass.
See also
236
www.PacktPub.com
Stay Connected: