Forward Advance Learning

Nesting

CSS selectors allow us to chain selectors together. If we write:

.homepage article {
padding:10px;
}

...this will match any article inside an element with a class of homepage.

This is tremendously useful, but quickly becomes painful to write. Consider the following CSS:

aside.sidebar nav li {
margin-left:10px;
}
aside.sidebar nav li li {
margin-left:20px;
}

Imagine we had 100 rules to apply to our aside.sidebar nav. We would get bored of repeatedly namespacing everything pretty quickly.

Nesting SASS for fun and glory

SASS lets us nest our selectors, like so:

aside.sidebar {
nav {
li {
margin-left:10px;
li {
margin-left:20px;
}
}
}
}

This will compile down to the CSS above.

Namespacing

This is very useful for namespacing. We might create a class for rendering a user profile, like so:

<div class="standard_user_profile">
Stuff in here
</div>

We can then namespace our SASS:

.standard_user_profile {
// further style rules
}

We might apply a style to the body tag, then namespace everything on a particular page, so that we can combine all our CSS into a single download.

Exercise - Nested Sass

Grab the exercise start point. Write nested queries to style the header with a horizontal nav bar, nicely positioned h1, and pretty background colour.

&

Sometimes we want to append styles to the current style. For this we have the ampersand (&) selector.

Say we want a hover state. If we wrote this:

a {
color:red;
:hover {
color: blue;
}
}

the generated CSS would look like this

a :hover {
color: blue
}

Notice the space. This would match an anchor containing a hovered item, rather than matching a hovered anchor. To fix this we use the & parent selector, like so:

a {
color:red;
&:hover {
color: blue;
}
}

This will give us this:

a:hover {
color: blue
}

Exercise - Hover states

Add hover states to the sidebar and header navigations.

Responsive design

We can use nesting to create a responsive design.

Say we want our user component to respond at a particular width. We might define set widths:

$desktop: 1000px
$tablet: 780px;
$iphone: 480px;

Then we can apply style rules to specific parts of our page at specific widths:

.standard_user_profile {
background: red;
@media (max-width: $mobile) {
background: blue;
}
}

Exercise - Responsive Design

Create a two column float layout by floating the aside left with a width, and the article right, with a width, like this:

aside {
float:left;
width: $desktop * 0.25 - 100;
}
article {
float:right;
width: $desktop * 0.75 - 100;
}
footer {
clear:both;
}

Now add style so that when the width drops to tablet width, the widths of the aside and article adjust accordingly.

Add a further rule so that, when the page drops below iPhone width, the article and aside become:

width:auto;
float:none;

Further Exercise

Style the header, so that it responds nicely to the page width.