19 4 / 2012

Make CSS fun again with SASS!

CSS is powerful, with few changes you can make your website look completely different. You can easily separate design from markup and create amazing designs. Although CSS is simple I used to have a hard time structuring my documents and I often ended up with lots of duplicated rules. That ended when I found SASS, which in my opinion is the biggest revolution of web development ever.

So, what is SASS?

Sass stands for “Syntactically Awesome Stylesheets” and comes in two flavors. SASS, the original format with indented syntax and SCSS which is CSS compatible. Since I’m an old school user I’ll focus on the SASS format in this article.

This quote comes from the official site and describes the purpose well:

Sass is a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.

Nice huh, but why would you use it?

Before I’ll show some examples I really hope to sell this so you so here are some benefits:

  • I’ve saved hundreds and hundreds of hours in the 3 - 4 years that I’ve used SASS.
  • I have never used the find and replace function in a CSS file since then.
  • I have never scrolled down a 10000 lines long file trying to find a specific rule.

import files

In SASS a file named style.sass would be compiled to a file called style.css. If you prepend the filename with an underscore the file won’t be compiled at all and you can include it within another file. This makes is easy to keep a logic structure of rules, for example:

@import 'reset'

@media only screen and (min-width: 768px)
  @import 'tablet'

@media only screen and (max-width: 480px)
  @import 'mobile'

The file above is named style.sass and includes all the rules in the file called _reset.sass. As mentioned before SASS uses syntactical whitespace and nesting so the rules within the file called _tablet.sass would only be applied inside the first media query. Sass will compile style.sass into a single file but you can structure the rules in as many files that you want.

Variables

You can use even use variables to define rules. This was the feature i missed the most while I was hacking CSS. Define colors, margins, paddings or anything else you want to be able to easily change.

$link_color: #007bc0

a:link, a:visted
  color: #{$link_color}

You can even perform calculations:

$link_hover_color: $link_color - #111

a:hover, a:active
  color: #{$link_hover_color}

This makes it very easy to change colors

Mixins

Mixins is a really powerful feature of SASS which makes it possible to reuse blocks of rules on any given selector. Are your tired of retyping the same vendor prefixes over and over again? I sure was. Check out this example:

@mixin border_radius($top, $right: '', $bottom: '', $left: '')
  @if $right == ''
    -moz-border-radius: #{$top}px #{$top}px #{$top}px #{$top}px
    -webkit-border-radius: #{$top}px #{$top}px #{$top}px #{$top}px
    border-radius: #{$top}px #{$top}px #{$top}px #{$top}px
  @else
    -moz-border-radius: #{$top}px #{$right}px #{$bottom}px #{$left}px
    -webkit-border-radius: #{$top}px #{$right}px #{$bottom}px #{$left}px
    border-radius: #{$top}px #{$right}px #{$bottom}px #{$left}px

This mixin defines a set of rules for any element. Use it like this:

#call-to-action
  @include border_radius(10px)

If you want different radius for different corners, then just add more arguments:

#call-to-action
  @include border_radius(10px, 4px, 16px, 12px)

Mixins makes it fun to try out new features of CSS since you can generate all the vendor prefixes dynamically, but it doesn’t stop there. Imagine the relief of removing all the duplication in a bloated CSS file.

Other resources

Conclusion

I hope I’m a good enough writer to make you see how powerful this is. As stated before this saves a lot of time and makes CSS fun.

Happy SASSing!

Written by:

29 3 / 2012

Make Click Areas Comfortably Large

Have you ever been browsing a web site on your smart phone or tablet and found that on some sites, the links are so tiny and so tightly packed, that it’s near impossible to click the right one?

I have definitely been there and it’s equally frustrating each time. As the use of smart phones and tablets increases, so does the importance of having big enough target areas to interact with. But it’s not only important for mobile browsing. The truth is that it benefits desktop users as well.

Fitts’s Law

Fitts’s Law is a classic rule of thumb in Usability. The law can be expressed in a fairly complex mathematical way but in a nutshell it states that the larger and closer a target is, the easier and faster it is to click it.

It’s not exactly Rocket Science, but still it highlights the importance of having, not only big enough targets, but also to position them intelligently.

If you want to know more about Fitts’s Law there’s an excellent explanation over at Particle Tree.

Designing for Touch

For touch devices, such as smart phones and tablets, a big enough touch target is even more important than on desktop. While a mouse pointer is a precision instrument with a click area of just 1 x 1 pixel, a human finger is more of a sledge hammer. The avarage size of the pad of a human index finger is 1.6 to 2 cm which translates to about 45-57 pixels on a screen.

You’ve probably experienced the frustration yourself when trying to click small links that are tightly packed on a smart phone. It can be really hard to hit the right target and that’s not the experience you want people to have with your web site.

Image credit: sochacki.info

Recommended touch target sizes

Apple iOS Human Interface Guidelines state that a touch target should be at least 44 x 44 points large. (The reason they’re using points instead of pixels is that points can be used for both standard and retina displays).

Microsoft’s Windows Phone UI Design and Interaction Guide suggest that the size of the touch target should be 34 pixels with an absolute minimum of 26 pixels and Nokia’s Developer Guidelines state that the touch target should be at least 1 x 1 cm.

I actually I think that Nokia has the best guidelines since it states its minimum dimensions in cm. I mean 44 pixels can be very different on different screens and devices.

What you don’t have in size you can make up in space

Another interesting aspect of this is that if you absolutely do need to have relatively small touch targets you can partly compensate that by increasing the space between the targets. By doing that you limit the chance of missed targets.

The rule is: The smaller the target, the bigger the gap.

In Practice

Enough already, I think you get why it’s important to have big enough click/touch targets. The question is, how is it done in practice?

The first thing to recognize is that the clickable area could be well outside the visible area of the object.

Regular links

For links in a list, the easiest way is to increase the padding. Instead of having a padding on the list-item you should have it on the link itself. In this example I simply add a 10 pixel padding to a link. Watch how that dramatically increases its clickable area (The faint red background indicates the clickable area).

li a {
  padding: 10px;
}

Checkboxes and Radiobuttons

For checkboxes and radiobuttons, which often are really small, the trick is to put them inside a label and add a generous padding to them. By connecting the checkbox and the label via the id and the for attributes, the entire area of the label toggles the checkbox.

HTML

<label for="foo">
   <input type="checkbox" name="foo" id="foo" value="bar" />
  A padded checkbox
<label>

CSS

label {
  display: block
  padding: 10px;
}

In this case the padded click area is over 50 times larger than the checkbox.

Of course there are other elements that this could be applied to as well but these two examples should be enough to give you an idea of how to go about it.

References

Online

Finger-Friendly Design: Ideal Mobile Touchscreen Target Sizes

Touch Target Sizes

The Definitive Guide To Styling Web Links

Written by: Gabriel Svennerberg

01 3 / 2012

The Proper Way to Include CSS

You already know that the CSS should be separated from the HTML not to violate the separation of concerns. You probably also know that it should be inserted in the <head> part of the page. But what is the best way to include it? There is after all two ways of doing it.

  • Via <link>
  • Via @import

At first glance it might seem that it wouldn’t matter, but as it turns out it does. In fact it does matter a lot!

Using @import to include CSS can cause a blank white screen, just like if you would have inserted the CSS at the bottom of the page.

It does this becuase CSS inserted via @import is always downloaded last. Since the browser won’t render anything until it loaded all the CSS, the page is completely blank until the CSS has finally downloaded.

But why does the browser wait until all the CSS is loaded? Because it’s lazy! It doesn’t want to risk having to rerender the content, something it have to do if the CSS will alter the styling (which it probably will).

Actual Performance vs Percieved Performance

It’s important to understand that this behavior doesn’t affect the actual performance of the page. In fact in some cases the actual performance is faster. What it does affect is the percieved performance.

With the CSS being loaded first, the browser will render the content of the page as it’s being downloaded. This is called Progressive rendering and it gives the user the impression that the page is loading faster.

The rule

What it boiles down to is this:

Always use <link> in the <head> of the document to include CSS.

<link type="text/css" rel="stylesheet" media="screen" href="style.css" />

Related

CSS in the <head>

References

Books

High Performance Web Sites - Essential Knowledge for Frontend Engineers by Steve Souders

Online

Don’t use @import

Bonus Fact

This best practice is taken from rule no 5 in Steve Souders excellent book High Performance Web Site. This book contains 14 rules for faster-loading pages and is a must read if you’re serious about web site performance.

Written by: Gabriel Svennerberg

19 1 / 2012

CSS in the Head

When optimizing a page you’re obviously thinking about where to add different assets on it. Stuff that is needed up front is placed at the top and stuff that is needed later can be placed further down. After all, we want the page to show something as fast as possible!

The percieved performance in this case is the most important factor. We therefore want the page to load progressively, meaning: The page renders from top to bottom as content is being downloaded.

Lets say you’re building an image gallery to show off your fabolous collection of Ninja Toasters(!?). When the user clicks a toaster a lightbox will open and display a bigger image of the toaster.

Now, the CSS for the lightbox isn’t needed for rendering the page. It’s actually not needed until the user clicks an image. Therefore we could include it at the bottom of the page to let other content load first right. You know so that the page will render faster? Wrong! Contrary to common sense it will actually delay the rendering of the page in a lot of web browsers.

But why does it delay the rendering? Keeping the browser from downloading it before other content ought to make the rendering faster. This is really counter intuitive at first glance, but listen to this:

The browser doesn’t want to risk having to re-render the page, it therefore waits until all CSS is loaded before rendering anything!

Fortunally there’s a really simple solution to this, just follow this simple rule: Include all CSS in the <head> of the page.

References

Books

High Performance Web Sites - Essential Knowledge for Frontend Engineers by Steve Souders

Online

Best Practices for Speeding Up Your Web Site

Written by: Gabriel Svennerberg

Tags:

Permalink 2 notes

12 1 / 2012

Separation of Concerns

Have you ever found yourself in a situation where you have a site where the HTML, the CSS and the JavaScript are all tangled together and it becomes a nightmare to make even the tiniest site-wide change?

What you’ve experienced is what is commonly referred to as Spaghetti code. To avoid falling into this trap you should follow one simple rule:

Always separate HTML, CSS and JavaScript into different files.

Remember that HTML is for content (and structure), CSS is for design and JavaScript is for behavior. By separating them into different layers you gain several things. It becomes:

  • Easier to maintain
  • Increased performance
  • Better accessibility
  • A good foundation for SEO

Maintainability

First of all, your code becomes more maintainable. If there’s something wrong with the design, it’s probably in the CSS. If on the hand your super cool drag and drop interface stops working, something is probably wrong in the JavaScript files. In other words, it’s easier to find errors.

Imagine wanting to change the entire design of your site to a ninja unicorn theme (shudder). Having your HTML, CSS and JavaScript in a big mess you basically need to rewrite the whole site. But if you been a good coder and kept them separated, all you need to do is to change the CSS. Simple, right?

Performance

In most cases the site loads faster if you have the layers separated. And we all know how important speed is!

JavaScript and CSS files are static assets that can be effectively cached by the browser. What it means is that the browser doesn’t have to download them more than once. You save both bandwidth and rendering time.

Accessibility

By separating the different layers you also benefit the accessibility of the site. It’s in fact the foundation of Progressive Enhancement (and graceful degradation). This means that even if the user interact with your site using a less capable device (for example: disabled JavaScript, screen reader, old browser, you name it) it can still access the content because the device can simply ignore the parts it doesn’t support and render what it can.

HTML is the solid foundation of the web. By making sure that you keep the content there (semantically marked up of course) and that neither the CSS, nor the JavaScript is in its way, you can be sure that every browser on this planet can access your content.

SEO

Web crawlers, the evil robots of Search Engines that constantly crawles the web on their endless hunt for content to index, is another reason you want to separate the layers. A web crawler is basically a blind user. It doesn’t care about your fancy styles or your crazy JavaScript animations. All it cares about is your content - your HTML.

So you better make sure that your content is semantically marked up with valid HTML and that the CSS and JavaScript is out of its way. Having done this, you’re on your merry way towards SEO nirvana.

A Bad Example (Warning Anti Pattern!)

In this example, the separation of concerns is violated. Both content, style and behavior are meshed together in an awful soup.

HTML

<a href="/some/url/" onclick="someFunction(); return false;" style="font-size: 12px; color: #f00;">A bad link</a>

Good Example

In this good example the same thing is done with a clear separation between content, style and behavior.

HTML

<a href="/some/url/" id="some_link">A good link</a>

CSS

#some_link { font-size: 12px; color: #f00; }

JavaScript

document.getElementById('some_link').addEventListener('click', someFunction, false);

Conclusion

I hope that this article have convinced you that keeping a clear separation is the way to go. So save yourself a lot of grief and separate these three levels as much as possible or you might as well end up in Spagetti Code Hell.

References

Online

The Web Standards model - HTML, CSS and JavaScript

Separation of concerns on Wikipedia

Books

DOM Scripting by Jeremy Keith, FriendsofEd 2005

Bulletproof Web Design by Dan Cederholm, New Riders 2006

Bonus Fact

The concept of Separation of Concerns is not limited to HTML, CSS and JavaScript. It applies just as much to general software development where you want to keep different things separated. For example the data, the business logic and the User Interface.

Separation of concerns on Wikipedia

Written by: Gabriel Svennerberg

Tags:

Permalink 31 notes