Professional CSS3

5 (5 reviews total)
By Piotr Sikora
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Foundations and Tools

About this book

CSS is the preferred technology to design modern web pages. Although CSS is often perceived as a simple language, applying modern styles to web pages with CSS and maintaining the code for larger websites can be quite tricky.

We will take you right from understanding CSS to designing high-quality web pages in CSS3. We'll quickly take you through CSS3's features, and show you how to resolve common issues so you can build your basic framework. Finally, you will learn about code architecture and CSS methodologies used in scalable apps and you'll explore the various new features of CSS3, such as FlexBox, to help you create the most modern layout methodologies. By the end of the book, you will be a master at creating pure CSS web pages and will know sophisticated web design techniques, giving you an edge over other web designers.

Publication date:
May 2016
Publisher
Packt
Pages
362
ISBN
9781785880940

 

Chapter 1. Foundations and Tools

It is important to learn about the foundations in each area. You need to have basic information to be a professional. Good usage of tools is almost as important as the foundation. Without good tools, your foundation won't be used well.

This chapter is about tools that will help to build better CSS code. It describes features of preprocessors and finally the foundation knowledge about SASS. In this chapter, you can get basic knowledge about automatization of repeatable processes in frontend development with GULP.js. Finally, you can find an example of file structure, which will partialize your project into small, easy to edit, and maintainable files.

In this chapter, we will:

  • Learn about the usage of preprocessors.

  • Create a CSS project with a proper structure.

 

Choosing the right IDE


Building CSS code is pretty simple. If you want to start, you just need a simple text editor and start writing your code. If you want to speed up the process, you will need to choose the right text editor or integrated development environment (IDE). Currently the most popular editors/IDEs for frontend developers are as follows:

  • Sublime Text

  • Atom

  • WebStorm/PHPStorm

  • Eclipse/Aptana

  • Brackets

Your choice will be based on price and quality. You should use the editor that you feel most comfortable with.

Speeding up the programming process with snippets/Emmet

When you are creating a code, you have parts of codes that you repeat in all projects/files. You will need to create snippets that will help you to speed up the process of writing code. As a frontend developer, I recommend you to get a basic knowledge about Emmet (previously Zen Coding). This is a collection of HTML/CSS snippets, which will help you build code faster. How to use it? It is basically included in modern frontend editors (Sublime Text, Atom, Brackets, WebStorm, and so on). If you want to check how Emmet works in CSS you need to start a declaration of some class for example .className, open the brackets ({}) and write for example:

pl

Then press the Tab button, which will trigger the Emmet snippet. As a result, you will get the following:

padding-left

Following are examples of the most used properties and values:

Emmet form

Result

bg

Background

bgc

Background color

m

Margin

ml, mr, mt, mb

Margin-left, margin-right, margin-top, margin-bottom

ml20px

Margin-left: 20px

c

Color

fl

Float: left

p20px20p

Padding: 20px 20%

tac

Text-align: center

tdn

Text-decoration: none

ttu

Text-transform: uppercase

dib

Display: inline-block

!

!important

For a better understanding of Emmet and to get a full list of features, it is recommended to check the official website of the project at: http://emmet.io/.

Keyboard shortcuts

Do you remember when you learned the most impressive keyboard shortcuts Ctrl + C ,Ctrl + V? It helped you to save about 2 seconds each time you wanted to make an operation of copying and pasting some text or any other element. But what about automizing some processes in building code? Yeah, it's going to be helpful and you can do it with keyboard shortcuts.

Shortcuts that you should know in your IDE are as follows:

  • Duplicating line

  • Deleting line

  • Moving line

  • Formatting code

 

Cross browser compatibility – which browsers should you install?


To test your code, you will need all the modern web browsers. In your list, you should have the following browsers:

  • Google Chrome (newest version)

  • Mozilla Firefox (newest version)

  • Mozilla Firefox developers edition (newest version)

  • Opera (newest version)

  • Safari (newest version)

  • Internet Explorer

Internet Explorer (IE) is the biggest issue in frontend developers' lives because you will need a bunch of IEs on your machine, for example, 9, 10, and 11. The list is getting smaller because back in the days the list was longer. IE6, 7, 8, 9, and so on. Now IE6, 7, and 8 are mostly not supported by the biggest web projects like YouTube and Facebook. But it sometimes occurs in big companies in which the changing of operating systems is a pretty complicated process.

To easily test your code on a bunch of browsers, it is good to use online tools dedicated for this test:

But an easy and free way to do it is to create a virtual machine on your computer and use the system and browser which you need. To collect the required versions of IE, you can refer to http://modern.ie. With modern.ie, you can select the IE version you need and your version of virtual machine platform (VirtualBox, Parallels, Vagrant, VMware).

How to use inspector

Dealing with HTML and CSS code is almost impossible nowadays without inspector. In this tool, you can see the markup and CSS. Additionally, you can see the box model. This is well known too in browsers for web developers. A few years ago, everybody was using Firebug dedicated for Firefox. Now each modern browser has its own built-in inspector, which helps you to debug a code.

The easiest way to invoke inspector is to right-click on an element and choose Inspect. In Chrome, you can do it with a key shortcut. In Windows, you have to press F12. In MAC OSX, you can use cmd + alt + I to invoke inspector.

Key shortcuts

For faster using of your browser, it's good to know some key combinations that will speed up the process.

Key combination

Function

Ctrl + R, cmd + R

Reload

Ctrl + Shift + R, cmd + shift + R

Reload with cache

cmd + I, F12

Inspector

Ctrl + U, cmd + alt + U

Source of page

 

Preprocessor – why should you use them?


A preprocessor is a program that will build CSS code from other syntax similar or almost identical to CSS. The main advantages of preprocessors are as follows:

  • Code nesting

  • Ability of using variables

  • Ability of creating mixins

  • Ability of using mathematical/logical operations

  • Ability of using loops and conditions

  • Joining of multiple files

Nesting elements in preprocessors

Preprocessors give you the advantage of building code with nesting of declarations. In simple CSS, you have to write the following:

.class {
  property: value;
}
.class .insideClass {
  property: value;
}

In the preprocessor, you just need to write the following:

.class {
  property: value;

  .insideClass {
    property: value;
  }
}

Or in SASS with the following indentation:

.class
  property: value

  .insideClass
    property: value

And it will simply compile to code:

.class {
  property: value;
}
.class .insideClass {
  property: value;
}

The proper usage of nesting will give you the best results. You need to know that good CSS code.

Using variables to parametrize your CSS code

In good CSS code, there is no possibility to use variables in all browsers. Sometimes you are using same value in the few places, but when you have change requests from client/project manager/account manager, you just immediately need to change some colors/margins, and so on. In CSS, usage of variables is not supported in old versions of Internet Explorer. Usage of variables is possible with CSS preprocessors.

Using mixins in preprocessors

In classic programming language, you can use functions to execute some math operations or do something else like displaying text. In CSS, you haven't got this feature, but in preprocessors you can create mixins. For example, you need prefixes for border-radius (old IE, Opera versions):

-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;

You can create a mixin (in SASS):

@mixin borderRadius($radius) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  border-radius: $radius;
}

And then invoke it:

@include borderRadius(20px)

Mathematical operations

In preprocessors, you can use math operations like the following:

  • Addition

  • Subtraction

  • Multiplying

  • Dividing

As an example, we can create simple grid system. You will need, for example, 10 columns with a resolution of 1,000 pixels:

$wrapperWidth: 1000px;
$columnsNumber: 10;
$innerPadding: 10px;

$widthOfColumn = $wrapperWidth / $columnsNumber;

.wrapper {
  width: $wrapperWidth;
}

.column {
  width: $widthOfColumn;
  padding: 0 10px;
}

Logic operations and loops

Without a logical operator's comparison of operations and loops, you cannot create a good program in classic programming language. The same applies to preprocessors. You need them to automatize the creation of classes/mixins, and so on. The following is the list of possible operators and loops.

The list of comparison operators is as follows:

  • <: less than

  • >: greater than

  • ==: equal to

  • !=: not equal to

  • <=: less or equal than

  • >=: greater or equal than

The list of logical operators is as follows:

  • and

  • or

  • not

The list of loops is as follows:

  • if

  • for

  • each

  • while

Joining of multiple files

In classic CSS, you can import files into one CSS document. But in a browser, it still makes additional requests to the server. So, let's say when you have a file with the following content:

@import "typography.css"
@import "blocks.css"
@import "main.css"
@import "single.css"

It will generate four additional requests to CSS files. With a preprocessor, each @import makes a merging for you, and in this place you will have the content of the mentioned file. So, finally, you have four files in one.

Less – a short introduction

Less is a preprocessor mainly used in a Bootstrap framework. It has all the features of a preprocessor (mixins, math, nesting, and variables).

One of the good features is the quick invoking of declared mixins. For example, you have created a class:

.text-settings {
  font-size: 12px;
  font-family: Arial;
  text-align: center;
}

Then you can add declared properties with its values in other elements declared in your less file (it works like a mixin):

p {
  .text-settings;
  color: red;
}

You will finally get the following:

p {
  font-size: 12px;
  font-family: Arial;
  text-align: center;
  color: red;
}

CSS with Stylus

Stylus has two versions of code (like SASS): one with braces/semicolons and the other without braces/semicolons. Additionally (over SASS), you can omit colons. If it continues to be developed and still retains its present features, it's going to be the biggest competitor for SASS.

SASS – the most mature preprocessor

SASS stands for Syntactically Awesome Stylesheets. It first appeared in 2006 and was mainly connected to Ruby on Rails (RoR) projects. Agile methodology used in RoR had an influence on frontend development. This is currently the best known CSS preprocessor used in the Foundation framework with the combination of Compass. A new version of the Twitter Bootstrap (fourth version) framework is going to be based on SASS too.

In SASS, you can write code in a CSS-like version called SCSS. This version of code looks pretty similar to CSS syntax:

a {
  color: #000;

  &:hover {
    color: #f00;
  }
}

The second version of code is SASS. It uses indentations and is the same as the preceding code, but written in SASS:

a 
  color: #000;
  
  &:hover 
         color: #f00;

You can see bigger differences in mixins. To invoke a mixin in SCSS, write the following:

@include nameOfMixin()

To invoke a mixin in SASS, write the following:

+nameOfMixin()

As you can see, SASS is a shorter version than SCSS. Because of the shortcuts and the automatization processes it is highly recommend to use SASS over SCSS—write Less—get more.

Personally I'm using SASS. Why? The first reason is its structure. It looks very similar to Jade (an HTML preprocessor). Both of them are based on indentation and it is easy stylize Jade code. The second reason is the shorter versions of functions (especially mixins). And the third reason is its readability. Sometimes, when your code is bigger, the nesting in SCSS looks like a big mess. If you want, for example, to change a nested class to be in any other element, you have to change your {}. In SASS, you are just dealing with indentation.

Short comparison

I've been working a lot with Less and SASS. Why did I finally chose SASS? Because of the following reasons:

  • It's a mature preprocessor

  • It has very good math operations

  • It has extensions (Compass, Bourbon)

Usage of Compass is recommended because:

  • It has a collection of modern mixins

  • It creates sprites

Most preprocessors have the same options and the reason you will choose one is your own preferences. In this book, I will be using SASS and Compass. In the following table, you can find a short comparison:

 

Less

Stylus

SASS

Variables

Yes

Yes

Yes

Nesting

Yes

Yes

Yes

Mixins

Yes

Yes

Yes

Math

Yes

Yes

Yes

Additional collections of mixins

No

No

Yes (Compass/Bourbon)

 

SASS foundation


Using the SASS preprocessor is really simple. You can use it in two ways: SCSS and SASS itself. Using the SASS preprocessor is really simple. You can use it in two ways: SCSS and SASS. The SCSS syntax looks like extended CSS. You can nest your definitions using new braces. SASS syntax is based on indent (similar for example to Python language).

Variables – where and how to use

Using variables is the essential feature of SASS, which is mostly impossible in CSS that is used on most modern browsers. Variables can be used in every element that you want to parametrize, such as colors, margins, paddings, and fonts.

To define variables in SASS, you just need to do it with the $ sign and add the name of your variable after it.

In SCSS:

$color_blue: blue;

Usage:

.className {
  color: $color_blue;
}

Simple mixins – where and how to use (@mixin, @include)

As mentioned in the previous section, variables can be used to parametrize the code. The second best known feature is to add some predefined block of code that you can invoke with some shorter version.

In SCSS, you can predefine it this way:

@mixin animateAll($time) {
  -webkit-transition: all $time ease-in-out;
  -moz-transition: all $time ease-in-out ;
  -o-transition: all $time ease-in-out;
  transition: all $time ease-in-out;
}

And then invoke with:

@include animateAll(5s)

In the SASS version:

=animateAll($time)
  -webkit-transition: all $time ease-in-out
  -moz-transition: all $time ease-in-out
  -o-transition: all $time ease-in-out
  transition: all $time ease-in-out

And invoke it with:

+animateAll(5s)

Example:

SASS:

.animatedElement
  +animateAll(5s)

Compiled CSS:

.animatedElement {
    -webkit-transition: all 5s ease-in-out;
    -moz-transition: all 5s ease-in-out;
    -o-transition: all 5s ease-in-out;
    transition: all 5s ease-in-out;
}

Extending classes (@extend)

What does @extend make in SASS code? For example, you have a part of code that is repeating in all fonts:

.font-small {
  font-family: Arial;
  font-size: 12px;
  font-weight: normal;
}

And you don't want to repeat this part of code in the next selector. You will write in SASS:

.font-small-red {
  @extend .font-small;
  color: red;
}

The code it will generate will look like the following:

.font-small, .font-small-red {
    font-family: Arial;
    font-size: 12px;
    font-weight: normal;
}

.font-small-red {
    color: red;
}

This SASS feature is great to build optimized code. Remember to use it in your project over mixins, which will generate more code.

Importing files (@import)

In CSS, you could import CSS files into one root file with @import. For example:

@import "typography.css"
@import "grid.css"

In SASS, you can import SASS/SCSS files into one with an automatic merge option. In case you have, for example, two files that you want to include in one SASS file, you need to write the following code:

@import "typography"
@import "grid"

As you can see in the preceding code, you don't need to add an extension of the file into import as it automatically loads the SASS or SCSS file. The only thing you need to remember is to have only one file in this example named, typography.

Let's check how it will behave in real code. Imagine that we have two files, _typography.sass and _grid.sass.

File _grid.sass:

.grid-1of2
  float: left
  width: 50%

.grid-1of4
  float: left
  width: 25%

.grid-1of5
  float: left
  width: 20%

File _typography.sass:

body
  font-size: 12px

h1, h2, h3, h4, h5, h6
  font:
    family: Arial

h1
  font:
    size: 36px

h2
  font:
    size: 32px

h3
  font:
    size: 28px

h4
  font:
    size: 24px

h5
  font:
    size: 20px

h6
  font:
    size: 16px

Now let's create a style.sass file:

@import _typography
@import _grid

After compilation of style.sass, you will see a style.css file:

body {
    font-size: 12px;
}

h1, h2, h3, h4, h5, h6 {
    font-family: Arial;
}

h1 {
    font-size: 36px;
}

h2 {
    font-size: 32px;
}

h3 {
    font-size: 28px;
}

h4 {
    font-size: 24px;
}

h5 {
    font-size: 20px;
}

h6 {
    font-size: 16px;
}

.grid-1of2 {
    float: left;
    width: 50%;
}

.grid-1of4 {
    float: left;
    width: 25%;
}

.grid-1of5 {
    float: left;
    width: 2%;
}

As you can see, two files are merged into one CSS, so, additionally, we made a small optimization of code because we reduced the number of requests to the server. In case of three files, we have three requests (style.css, then typography.css, and grid.css). Now there will be only one request.

Using of & in SASS

Sometimes, in nesting, you will need to use the name of the selector that you are currently describing. As a best description of the problem, you need to first describe a link:

a {
  color: #000;
}

and then:

a:hover {
  color: #f00;
}

In SCSS, you can use & to do that:

a {
  color: #000;

&:hover {
    color: #f00;
  }
}

In SASS:

a
  color: #000

  &:hover
    color: #f00

You can resolve with this element other problems like combining names:

.classname {}

.classname_inside {}

In SCSS:

.classname {
  &_inside {

  }
}

In SASS:

.classname
  &_inside

This option has been possible since SASS 3.5. It will be very helpful in creating code build in BEM methodologies.

Compass features

Compass is a very useful SASS framework, especially when you are working with a big list of icons/reusable images. What you need to do is gather all the images in one folder in your project. For example, yourfolder/envelope.png and yourfloder/star.png.

Then in your SASS code:

@import "compass/utilities/sprites"
@import "yourfolder/*.png"
@include all-yourfolder-sprites

Then in your code, you can use images as an example:

.simple-class-envelope
  @extend .yourfolder-envelope

.simple-class-star
  @extend .yourfolder-star

And it will add a code to your classes:

.simple-class-envelope {
  background-image: url('spriteurl.png');
  background-position: -100px -200px;
}

Where -100px and -200px are examples of offset in your sprite.

 

Simple automatization (with Gulp)


Every time we are compiling project files (for example, Compass, Jade, image optimization, and so on), we are thinking about how we can automatize and speed up the process. The first idea—some terminal snippets and compiling invokers. But we can use grunt.js and gulp.js. What are Grunt and Gulp? In short—task runners. You can define a list of tasks, which you repeat all the time, group them into some logical structure, and run.

In most projects, you can use them to automatize a process of SASS/Compass compilation.

I assume that you have installed Node.js, Ruby, sass, and Compass. If not, I recommend you to do this first. To install all of the listed software, you need to visit:

On these pages, you can find guides and tutorials on how to install all of this software.

Then you will need to create a basic structure for your project. It is best to create folders:

  • src: In this folder we will keep our source files

  • dist: In this folder we will keep our compiled files

In the src folder, please create a css folder, which will keep our SASS files.

Then in the root folder, run the following command line:

npm init
npm install gulp-compass gulp --save-dev

In gulpfile.js add the following lines of code:

var gulp = require('gulp'),
    compass = require('gulp-compass');

gulp.task('compass', function () {
    return gulp.src('src/styles/main.sass')
        .pipe(compass({
            sass: 'src/styles',
            image: 'src/images',
            css: 'dist/css',
            sourcemap: true,
            style: 'compressed'
        }));
});

gulp.task('default', function () {
    gulp.watch('src/css/**/*.sass', ['compass']);
});

Now you can run your automatizer with the following in your command line:

gulp

This will run the default task from your gulpfile.js, which will add a watcher to the files with .sass extensions, which are located in the src/css folder. Every time you change any file in this location, your task compass will run. It means that it will run the compass task and create a sourcemap for us. We could use a default compass command, but gulp.js is a part of the modern frontend developer workflow. We will be adding new functions to this automatizer in the next chapters.

Let's analyze the code a little deeper:

gulp.task('default', function () {
    gulp.watch('src/css/**/*.sass', ['compass']);
});

The preceding code defines the default task. It appends a watcher, which checks the src/css/**/*.sass location for sass files. It means that every file in a src/css folder and any subsequent folder, for example, src/css/folder/file.sass, will have a watcher. When files in this location are changed, the task defined in the array [compass]will run. Our task compass is the only element in the array but it, of course, can be extended (we will do this in the next chapters).

Now let's analyze the task compass:

gulp.task('compass', function () {
    return gulp.src('src/styles/main.sass')
        .pipe(compass({
            sass: 'src/styles',
            image: 'src/images',
            css: 'dist/css',
            sourcemap: true,
            style: 'compressed'
      }));
});

It will compile the gulp.src('src/styles/main.sass)file and save the compiled file in pipe (gulp.dest('style.css')). The compass task is defined in pipe:

.pipe(compass({
            sass: 'src/styles',
            image: 'src/images',
            css: 'dist/css',
            sourcemap: true,
            style: 'compressed'
      }))

The first line of this task defines the source folder for SASS files. The second line defines the images folder. The third line sets the destination of the CSS file. The fourth line is set to generate a source map for the file (for easier debugging).The fifth line defines the style of the saved CSS file; in this case, it will be compressed (it means that it will be ready for production code).

 

Pixelperfect layouts tools


In a common workflow, a graphic designer creates the design of a website/application. Then, next in the process is the HTML/CSS coding. After the development process, the project is in the quality assurance (QA) phase. Sometimes it's focused only on the functional side of the project, but in a good workflow, it checks of graphic design phase. During the QA process, the designer is involved, he/she will find all pixels that are not good in your code. How would check all the details in a pixelperfect project?

The question is about mobile projects. How to check if it is still pixel perfect when it needs to be flexible in browsers? You will need to make it in described ranges. For example, you have to create HTML/CSS for the web page, which has three views for mobile, tablet, and desktop. You will need plugins, which will help you to build pixel perfect layouts.

Pixelfperfect plugin

Pixelperfect plugin will help you to compare design with your HTML/CSS in your browser. This plugin is available on Firefox and Chrome. To work with it, you need to make a screenshot of your design and add it in a plugin. Then you can set a position of image and opacity. This plugin is one of the most used by frontend developers to create pixel perfect HTML layouts.

MeasureIT plugin

This plugin will help you to keep proper distances between elements, fonts, and so on. As you can see in the following screenshot, it looks like a ruler over your web page. It is easy to use—just click on the plugin icon in the browser and then click on the website (it will start the ruler), and move the cursor to the place to which you want to know the distance, and voila!

 

Checking compatibility


Some CSS features don't work in all browsers. Some new properties need browser-specific prefixes (like -ms, -o, -webkit) to work properly across all modern browsers. But how to check if you can use some properties in your project? Of course, you can check it yourself, but the easiest way is to check it on http://caniuse.com/. You can open this web page and check which properties you can use.

 

Good assumptions in code


While you are creating CSS code, you have to remember initial assumptions that will help you to keep clear and very readable code. These assumptions are as follows:

  • Naming convention—You need to remember that your code needs to be the exact names of classes.

  • Use comments, but not everywhere, only in places where they are needed. Yeah, but when they are needed? They are especially needed when you have some exception or when you have some quick fixes for browsers. With comments, you can describe blocks of code, which describes the views, for example, of footer/header, or any other element.

  • Try to keep code which is readable and logical. But how does unlogical code look like? Look at the following two examples:

    Example 1 is as follows:

    .classname {
      font-size: 12px;
      color: red;
      font-weight: bold;
      text-align: center;
      margin: 10px;
      padding-left: 2px;
      text-transform: uppercase;
    }

    Example 2 is as follows:

    .classname {
      margin: 10px;
      padding-left: 2px;
    
      font-size: 12px;
      font-weight: bold;
      text-align: center;
      text-transform: uppercase;
    
      color: red;
    }

Which code looks better? Yeah, of course, the second example because it has grouped declarations. First the description of the box model, then the font and text behaviors, and finally color. You can try to keep it in another hierarchy which will be more readable for you.

Using sample 2 in SASS:

.classname
  margin: 10px
  padding:
    left: 2px
  font:
    size: 12px
    weight: bold
  text:
    align: center
    transform: uppercase
  color: red

Isn't it shorter and more logical?

  • Create proper selectors (this will be described later in this chapter).

  • Create an elastic structure for your files.

 

Creating proper selectors


The main problem of the CSS coder is creating proper selectors. Knowledge about priors in selectors is mandatory. It will help you to omit the !important statement in your code and will help you to create smaller and more readable files.

Using IDs

Using of IDs in CSS is rather bad behavior. The foundation of HTML says that an ID is unique and should be used only once in an HTML code. It is good to omit IDs in CSS and use them only when it is the only way to style some element:

#id_name {
  property: value;
}

Usage of IDs in CSS code is bad behavior because selectors based on ID are stronger than selectors based on classes. This is confusing in legacy code when you see that some part of the code is still preceded by another selector because it is added in the ID's parents-based selector as follows:

#someID .class {
    /* your code */
}

It is good to omit this problem in your projects. First, think twice if a selector based on an ID is a good idea in this place and if this cannot be replaced with any other "weaker" selector.

Using classes

Classes are the best friends of the HTML/CSS coder. They are reusable elements that you can define and then reuse as much as you want in your HTML code, for example:

.class_name {
  property: value;
}

Grouping selectors

You can group and nest selectors. First, let's nest them:

.class_wrapper .class_nested {
  property: value;
}

Then let's group them:

.class_wrapper_one,
.class_wrapper_two {
  property: value;
}

Interesting selectors

In CSS code, you need to be a selector specialist. It is a very important skill to make a right selector that will match a specific element in the DOM structure. Let's provide a little bit of fundamental knowledge about selectors.

Adjacent sibling combinatory +

The plus sign in CSS can be used in selectors in which you will need to select an element right after the element on the left side of the plus sign, for example:

p + a {
  property: value;
}

This selector will return a, which is right after the p selector, like in the following example:

<p>Text</p>
<a>Text</a>

But it won't work in the following case:

<p>Text</p>
<h1>Text</h1>
<a>Text</a>

Child combinator ">"

With element (>) in the selector, you can match every element that is right into the element. Let's analyze the following example:

p >a {
    property: value;
}

This selector will return all <a> elements which are into<p> element but are not nested deeper, for example:

<p>
<a>text</a>
</p>

But this won't work in the following case:

<p>
<span>
<a>text</a>
</span>
</p>

Adjacent sibling combinatory ~

With ~, you can create a selector that will match every element that is parallel in the DOM structure, for example:

p ~ a {
    color: pink;
}

This selector will work in the following cases:

<p></p>
<a></a>

and:

<p>Text</p>
<span>Text</span>
<a>Text</a>

Getting elements by attributes

Sometimes, there is no way to create a selector based on elements, classes, and IDs. So this is the moment when you need to search for any other possibility to create the right selector. It is possible to get elements by their attributes (data, href, and so on):

[attribute] {
    property: value;
}

It will return the following:

<p attribute>text</p>

And will also return the following:

<p attribute="1">text</p>

Attributes with exact value [attribute="value"]

In real CSS/HTML code, there are examples when you will need a selector which is based on attributes with an exact value like inputs with the type as text or when elements data attribute is set with some value. It is possible with a selector which is similar to this example code:

input[type="text"] {
    background: #0000ff;
}

will match:

<input type="text">

Attributes which begin with [attribute^="value"]

This selector is very useful when you want to match elements with attributes that begin with some specific string. Let's check an example:

<div class="container">
    <div class="grid-1of4">Grid 2</div>
    <div class="grid-1of2">Grid 1</div>
    <div class="grid-1of4">Grid 3</div>
</div>

SASS code:

.grid-1of2
width: 50%
  background: blue

.grid-1of4
width: 25%
  background: green


[class^="grid"]
  float: left

Compiled CSS:

.grid-1of2 {
    width: 50%;
    background: blue;
}

.grid-1of4 {
    width: 25%;
    background: green;
}

[class^="grid"] {
    float: left;
}

Let's analyze this fragment in SASS code:

[class^="grid"]
  float: left

This selector will match every element that has an attribute with a grid word in the beginning of this attribute. This will match in our case: .grid-1of2 and .grid-1of4. Of course, we could do it with SASS:

.grid-1of2, .grid-1of4
float: left

And get it in compiled code:

.grid-1of2, .grid-1of4 {
    float: left;
}

But let's imagine that we have about 10 or maybe 40 classes like the following:

.grid-2of4
  width: 50%

.grid-3of4
  width: 75%

.grid-1of5
  width: 20%

.grid-2of5
  width: 40%
.grid-3of5
  width: 60%

.grid-4of5
  width: 80%

In compiled CSS:

.grid-2of4 {
    width: 50%;
}

.grid-3of4 {
    width: 75%;
}

.grid-1of5 {
    width: 20%;
}

.grid-2of5 {
    width: 40%;
}

.grid-3of5 {
    width: 60%;
}

.grid-4of5 {
    width: 80%;
}

And now we want to apply a float: left to these elements like:

.grid-1of2, .grid-1of4, .grid-2of4, .grid-3of4, .grid-1of5, .grid-2of5, .grid-3of5, .grid-4of5
  float: left

In CSS:

.grid-1of2, .grid-1of4, .grid-2of4, .grid-3of4, .grid-1of5, .grid-2of5, .grid-3of5, .grid-4of5 {
    float: left;
}

It is easier to use a selector based on [attribute^="value"] and match all of the elements with a class which starts with a grid string:

[class^="grid"]
  float: left

Whitespace separated attribute values [attribute~="value"]

With this selector you can match all elements which in list of "attributes" that contains a string described as a "value". Let's analyze the following example.

HTML:

<div class="container">
    <div data-style="green font10">Element green font10</div>
    <div data-style="black font24">Element black font24</div>
    <div data-style="blue font17">Element blue font17</div>
</div>

Now in SASS:

[data-style~="green"]
  color: green

[data-style~="black"]
  color: black

[data-style~="blue"]
  color: blue

[data-style~="font10"]
  font:
    size: 10px

[data-style~="font17"]
  font:
    size: 17px

[data-style~="font24"]
  font:
    size: 24px

Compiled CSS:

[data-style~="green"] {
    color: green;
}

[data-style~="black"] {
    color: black;
}

[data-style~="blue"] {
    color: blue;
}

[data-style~="font10"] {
    font-size: 10px;
}

[data-style~="font17"] {
    font-size: 17px;
}

[data-style~="font24"] {
    font-size: 24px;
}

And the effect in the browser is as follows:

Attribute values ending with [attribute$="value"]

In one of the previous sections, we had an example of a selector based on beginning of an attribute. But what if we need an attribute ending? With this feature comes a selector based on a pattern [attribute$="value"]. Let's check the following example code:

<div class="container">
    <a href="/contact-form">Contact form</a><br>
    <a href="/contact">Contact page</a><br>
    <a href="/recommendation-form">Recommendation form</a>
</div>

SASS:

[href$="form"]
  color: yellowgreen
font:
    weight: bold

Compiled CSS:

[href$="form"] {
  color: yellowgreen;
  font-weight: bold; 
}

The effect in the browser is as follows:

With the selector [href$="form"],we matched all elements whose attribute href ends with the string form.

Attributes containing strings [attribute*="value"]

With this selector, you can match every element that contains a string in a value in any place. Let's analyze the following example code.

HTML:

<div class="container">
    <a href="/contact-form">Contact form</a><br>
    <a href="/form-contact">Contact form</a><br>
    <a href="/rocommendation-form">Recommendation form</a><br>
    <a href="/rocommendation-and-contact-form">Recommendation and contact form</a>
</div>

SASS:

[href*="contact"]
  color: yellowgreen
  font:
    weight: bold

Compiled CSS:

[href*="contact"] {
    color: yellowgreen;
    font-weight: bold;
}

In the browser we will see:

With the selector [href*="contact"], we matched every element that contains the contact string in the value of the attribute href.

Using !important in CSS

Hah… the magic word in CSS, which you can see in some special cases. With !important, you can even overwrite inline code added by JavaScript in your HTML.

How to use it? It is very simple:

element {
    property: value !important;
}

Remember to use it properly and in cases where you really need it. Don't overuse it in your code because it can have a big impact in the future, especially in cases when somebody will read your code and will try to debug it.

 

Preparing your project


Starting your project and planning it is one of the most important processes. You need to create a simple strategy for keeping variables and mixins and also create a proper file structure. This chapter is about the most known problems in planning your file structure and the partialization of files in your project.

Files structure

The most important thing when you are starting a project is to make a good plan of its process. First, you will need to separate settings:

  • Fonts

  • Variables

  • Mixins

Then you will need to partialize your project. You will need to create files for repeatable elements along all sites:

  • Header

  • Footer

  • Forms

Then you will need to prepare next partialization—specific views of styling and elements, for example:

  • View home

  • View blog

  • View single post

  • View contact page

How to keep variables in a project

What can you keep in variables? Yeah, that is a good question, for sure:

  • Colors (of fonts, backgrounds, and elements)

  • Global font sizes (like H1-H6, p, and so on)

  • Grid dividers

  • Global paddings/margins

How and where to keep mixins (local and global)

In this file, you can collect your mostly used mixins. I've divided it into local and global. In global mixins, I'm gathering the most used mixins I'm using along all projects.

In local mixins, I recommend to gather those mixins that you will use only in this project:

  • Dedicated gradient

  • Font styling including font family size and so on

  • Hover/active states and so on

Keep typography styles in a separate file

This file is dedicated for all the most important text elements:

  • h1-h6

  • p

  • a

  • strong

  • span

Additionally, you can add classes like the following:

  • .h1-h6

  • .red .blue (or any other which you know that will repeat in your texts)

  • .small, .large

Why should you use classes like .h1-.h6?

Yeah, it's a pretty obvious question. Sometimes you cannot repeat h1-h6 elements, but, for example, on a blog, you need to make them the same font style as h1. This is the best usage of this style, for example (HTML structure):

<h1> Main title</h1>
<h2>Subtitle</h2>
<p>... Text block ... </p>

<h2>Second subtitle</h2>
<p>... Text block ... </p>

<p class="h2">Something important</p>
<p>... Text block ... </p>

<p class="h1">Something important</p>
<p>... Text block ... </p>

Views of specific elements

In the following listed files, you can gather all elements that are visible in some specific views. For example, in a blog structure, you can have a view of single post or page view. So you need to create files:

_view_singlepost.sass
_view_singlepage.sass
_view_contactpage.sass

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

 

Summary


In this chapter, you gathered information about the fundamentals of modern CSS workflow. We started with choosing an IDE and then we focused on speeding up the process through the usage of snippets, preprocessors, and processes automatization.

In the next chapter, we will focus on the basics of CSS theory, box models, positions, and displaying modes in CSS.

About the Author

  • Piotr Sikora

    Piotr Sikora is lead frontend developer at Nitro Digital, based in Kielce, Poland. He started working on web projects when he was in high school. Over the years, he has been a Flash developer, project manager, and team supervisor. He loves digital projects and dealing with all things digital.

    Piotr is a b-boy (break dancer) and has learned a lot of artistic stuff from dance. He teaches dance in his free time.

    Browse publications by this author

Latest Reviews

(5 reviews total)
It's worth giving a shot! I love this product.
Excellent
Excellent