Skip navigation
Help

Layout tools

warning: Creating default object from empty value in /var/www/vhosts/sayforward.com/subdomains/recorder/httpdocs/modules/taxonomy/taxonomy.pages.inc on line 33.
Original author: 
Scott Gilbertson

Look Ma, no floats! Image: Abobe

HTML5 and CSS 3 offer web developers new semantic tags, native animation tools, server-side fonts and much more, but that’s not the end of the story. In fact, for developers slogging away in the web design trenches, one of the most promising parts of CSS 3 is still just over the horizon — true page layout tools.

While it’s possible to create amazingly complex layouts using tools like CSS floats, positioning rules and the odd bit of JavaScript, none of those tools were actually created explicitly for laying out content, which is why it’s amazingly complex to get them working the way you want across browsers.

Soon, however, you’ll be able to throw out your floats and embrace a better way — the CSS Flexible Box Model, better known as simply Flexbox. Flexbox enables you to create complex layouts with only a few lines of code — no more floats and “clearfix” hacks.

Perhaps even more powerful — especially for those building responsive websites — the Flexbox order property allows you to create layouts completely independent of the HTML source order. Want the footer at the top of the page for some reason? No problem, just set your footer CSS to order: 1;. Flexbox also makes it possible to do vertical centering. Finally.

We’ve looked at Flexbox in the past, but, unfortunately the spec has undergone a serious re-write since then, which renders older code obsolete. If you’d like to get up to speed with the new syntax, the Adobe Developer Blog recently published a guide to working with Flexbox by developer Steven Bradley.

Bradley walks through the process of using Flexbox in both mobile and desktop layouts, rearranging source order and elements to get both layouts working with a fraction of the code it would take to do the same using floats and other, older layout tools. The best way to wrap your head around Flexbox is to see it in action, so be sure to follow the links to Bradley’s demo page using either Chrome, Opera or Firefox 20+.

For some it may still be too early to use Flexbox. Browser support is improving, but obviously older browsers will never support Flexbox, so bear that in mind. Opera 12 supports the new syntax, no prefix necessary. Chrome supports the new syntax, but needs the -webkit prefix. Like Opera, Firefox 20+ Firefox 22 supports the unprefixed version of the new spec. Prior to v22 (currently in the beta channel), Firefox supports the old syntax. IE 10 supports the older Flexbox syntax. Most mobile browsers support the older syntax, though that is starting to change. [Update: Mozilla developer Daniel Holbert, who is working on the Flexbox code in Firefox, wrote to let me know that the Flexbox support has been pushed back to Firefox 22. Actually the new Flexbox syntax is part of Firefox 20 and up, but until v22 arrives it's disabled by default. You can turn it on by heading to about:config and searching for layout.css.flexbox.enabled pref. Set it to true and the modern syntax will work.]

So, as of this writing, only two web browsers really support the new Flexbox syntax, though Firefox will make that three in the next month or so.

But there is a way to work around some of the issues. First off, check out Chris Coyier’s article on mixing the old and new syntaxes to get the widest possible browser support. Coyier’s methods will get your Flexbox layouts working in pretty much everything but IE 9 and below.

If you’re working on a personal site that might be okay — IE 9 and below would just get a simplified, linear layout. Or you could serve an extra stylesheet with some floats to older versions of IE (or use targeted CSS classes if you prefer). That defeats some of the benefits of Flexbox since you’ll be writing floats and the like for IE, but when usage drops off you can just dump that code and help move your site, and the web, forward.

0
Your rating: None

CSS Blend Modes demo. Image: Screenshot/Webmonkey.

We use the term “CSS 3″ all the time on Webmonkey, but technically that’s something of a misnomer. There is no spoon, you see.

In fact, the CSS Working Group, which oversees the CSS specification at the W3C, is cranking out draft specs of new features all the time — the monolithic “3.0″ or “4.0″ versioning was tossed out after CSS 2.1. Instead new features are developed as “modules” so that, for example, the Selector Module can be published without waiting for the Layout Module.

That means there are new CSS features coming all the time.

Adobe’s Divya Manian — who is also one of the developers behind HTML5 Boilerplate — recently gave a talk titled “CSS Next“, which highlights some of the exciting new CSS features coming soon to a browser near you.

Among the cool things Manian highlights are some impressive new tricks for web fonts, including better tools for working with ligatures, unicode and icon fonts.

There are also some impressive new layout tools in the works, namely CSS Regions and Exclusions. We looked at both back when Adobe first proposed them, but since then not only have they progressed to actual draft specs, but they’re now supported in Chrome’s Canary builds (rather than requiring a custom build from Adobe).

It’s still going to be a while before either can claim a spot in your CSS layout toolkit, but there are already a few demos you can check out to see the new layout possibilities Regions and Exclusions offer. Grab a copy of Chrome Canary and turn on “Enable Experimental WebKit Features” in chrome:flags and then point your browser to this demo of Regions and this “shape inside” demo of Exclusions.

Other things Manian covers that we’re looking forward to include CSS Filters and Blend modes. CSS Filters already work in WebKit browsers and allow you to apply effects like blur or grayscale to any HTML element. CSS Blend Modes work just like layer-blending modes in Photoshop and other graphics apps — allowing you to blend layers using modes like “difference,” “overlay,” “multiply” and so on. As of right now you still need a special build of Chromium to see Blend Modes in action.

Manian also covers two intriguing WebKit-only features that aren’t yet a part of any CSS spec, but could be one day. Be sure to read through Manian’s post for more info and a few other new things, including two Webmonkey has covered recently — CSS @supports and CSS Variables.

0
Your rating: None

Windows 8 will arrive in consumers’ hands later this week and with it will come the first official release of Internet Explorer 10.

It used to be that a new version of IE meant a new set of headaches for developers, but thankfully that’s no longer the case. In fact, when it comes to web standards support IE 10 stacks up pretty well against the competition.

IE 10 adds support for nearly a dozen new HTML5 APIs like Web Sockets, Web Workers, the History API, the Drag and Drop API and the File API. You can look over a complete list on Microsoft’s IE 10 Guide for Developers. There’s plenty of CSS support in this release as well; Animations, Transitions and Transforms are among the many new CSS tools. IE 10 also has experimental support for next-gen layout tools like CSS Grid Layout, CSS Multi-column Layout and CSS Regions.

For all that is good in IE 10 there are a couple of gotchas web developers should be aware of.

One is that, while IE 10 supports CSS Flexible Box Layout, it appears to support the older, now non-standard version of Flexbox (the documenation still uses the old syntax). Hopefully Microsoft will fix this with an update, but for the time being only Chrome and Opera have implemented the updated Flexbox syntax.

The other quirk of IE 10 is related to how the browser behaves on Windows 8 tablets. There are two “modes” in Windows 8, the classic desktop and the Metro UI. When IE 10 runs in Metro mode (which is the default) there’s a feature that allows you to “snap” a window to the side of the screen so you can have a browser window open alongside other applications. It’s a nice feature for users, but it has one quirk developer should be aware of — when snapped, IE10 ignores the meta viewport tag for any viewport smaller than 400 pixels in width. That means that your responsive layouts for smaller screens won’t trigger in snapped mode and your site will be scaled instead. Luckily there’s a fix. In fact developer Tim Kadlec has two solutions, one that uses pixels and one that does not. See Kadlec’s blog for full details.

It’s also worth noting that Microsoft is supporting the @viewport declaration rather than the viewport meta tag (IE 10 uses the prefix: @-ms-viewport). While the viewport meta tag is more widely supported (and used), it’s not currently part of any W3C spec, draft or otherwise. For more on @viewport, see the Opera developer blog. (Opera is currently the only other browser supporting @viewport.)

0
Your rating: None

The internet is disrupting many content-focused industries, and the publishing landscape is beginning its own transformation in response. Tools haven’t yet been developed to properly, semantically export long-form writing. Most books are encumbered by Digital Rights Management (DRM), a piracy-encouraging practice long since abandoned by the music industry. In the second article of a two-part series in this issue, Nick Disabato discusses the ramifications of these practices for various publishers and proposes a way forward, so we can all continue sharing information openly, in a way that benefits publishers, writers, and readers alike.

0
Your rating: None

Smashing-magazine-advertisement in 45 Fresh Useful JavaScript and jQuery Techniques and Tools
 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools  in 45 Fresh Useful JavaScript and jQuery Techniques and Tools  in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Yes, this is another round-up of fresh and useful Javascript techniques, tools and resources. But don’t close the tab yet, as you might find this one very useful. In this selection we present calendars, forms, buttons, navigation, debugging, optimization and compatibility tables as well as handy resources and tools. We also cover various jQuery-plugins that will help you extend the functionality of your website and improve user experience with ready components or coding solutions.

The last section also covers a number of useful educational resources such as a compilation of useful JavaScript coding practices, a detailed comparison of JavaScript frameworks and general JavaScript programming conventions. We are looking forward to your feedback.

You may be interested in the following related posts:

[Offtopic: by the way, did you know that Smashing Magazine has one of the most influential and popular Twitter accounts? Join our discussions and get updates about useful tools and resources — follow us on Twitter!]

Calendars and Timelines

jDigiClock – Digital Clock (HTC Hero inspired)
jDigiClock is a jQuery plugin inspired from HTC Hero Clock Widget.

Javascript-techniques-82 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jQuery Sliding Clock v1.1
jQuery transpearant Slider clock with CSS sprites.

Javascript-techniques-67 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Date / Time Picker
Note that this control is not designed to work in IE6; although it will function correctly in most cases, the positioning of the calendar may be way off depending on how your page is styled.

Javascript-techniques-05 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

JavaScript Debugging and Validation Tools

Venkman JavaScript Debugger project page
Venkman is the code name for Mozilla’s JavaScript Debugger. Venkman aims to provide a powerful JavaScript debugging environment for Gecko-based browsers namely Firefox 3.x, the Netscape 7.x series of browsers, Netscape 9.x series, Mozilla Seamonkey 1.x and Mozilla Seamonkey 2.x. It does not include Gecko-based browsers such as K-Meleon 1.x, Galeon 2.x and Netscape 8.x. The debugger is available as an add-on package in XPI format. Venkman JavaScript Debugger has been provided as part of the Mozilla install distribution since October 3rd 2001.

Javascript-techniques-14 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

CompanionJS
Companion.JS (pronounced Companion dot JS or CJS) is a Javascript debugger for IE.

Javascript-techniques-32 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

How to Test your JavaScript Code with QUnit
QUnit is a powerful JavaScript unit testing framework that helps you to debug code. It’s written by members of the jQuery team, and is the official test suite for jQuery. But QUnit is general enough to test any regular JavaScript code, and it’s even able to test server-side JavaScript via some JavaScript engine like Rhino or V8.

Javascript-techniques-44 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

JS Bin – Collaborative JavaScript Debugging
JS Bin is an open source collaborative JavaScript debugging tool.

Javascript-techniques-12 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Forms, Buttons & Navigation

Making a Google Wave History Slider
Here is shown how to create a Google Wave-like history slider. Using it will enable visitors to go back and forth in time to view the changes that take place on a comment thread.

Javascript-techniques-73 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Fancy Radio Buttons With jQuery
Creation of 2 mandatory option sets that a user could choose, while hiding off the radio button inputs and using an anchor links to make it a bit more usable.

Javascript-techniques-62 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Creative Button Animations with Sprites and JQuery
Fading hover effect for which the transition is smoothed with JavaScript, using jQuery library.

Javascript-techniques-83 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Password (un)Masking
JavaScript jQuery that toggles the masking and unmasking of the password field.

Javascript-techniques-68 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jQuery MagicLine Navigation
These “sliding” style navigation bars have been around a while, and turns out it’s really pretty darn easy. Here are put two examples together.

Javascript-techniques-49 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Fixed Fade Out Menu: A CSS and jQuery Tutorial
The aim is to have a fixed navigation that follows the user when he scrolls, and only subtly showing itself by fading out and becoming almost transparent. When the user hovers over it, the menu then becomes opaque again. Inside of the navigation we will have some links, a search input and a top and bottom button that let the user navigate to the top or the bottom of the page.

Javascript-techniques-52 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jQuery plugin: Simplest Twitter-like dynamic character count for textareas and input fields
The best way to explain what this plugin does is to mention Twitter. Twitter posts are limited to 140 characters. While typing the Twitter post there is this always present information about how many characters the users have before reaching the limit. The information is not only provided merely by displaying a number, there are different colors applied to certain stages to notify the user about the status.

Sliding Labels v2
Form label keeping the label inline, but sliding it off to the left rather than going away on click.

Javascript-techniques-87 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Ketchup Plugin
Ketchup is a slim jQuery Plugin that validates your forms. It aims to be very flexible and extendable for its appearance and functionality.

Javascript-techniques-84 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Layout tools

jQuery {css}designerGrid Plugin
{css} designerGrid is A jQuery Plugin developed for website interface developers who use the grid system of layout. {css} designerGrid is intended to assist these developers with CSS prototyping.

Javascript-techniques-80 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

css-template-layout
JavaScript (jQuery) implementation of the CSS Template Layout Module

Javascript-techniques-33 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

How to create a fluid grid with jQuery
Grid-based layout is probably the more preferred way to style up a webpage to give it more magazine-like look and feel. This tutorial is about how to use CSS and Javascript to create a fluid grid-based layout (See demo here). The algorithm/procedure used in this tutorial is very simple and straightforward. There are more advanced algorithms out there which can handle multiple scenarios. But the purpose is to understand the basic logic on how to create such layout. So here it goes…

Javascript-techniques-51 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

closure-templates
Closure Templates are a client- and server-side templating system that helps you dynamically build reusable HTML and UI elements. They are easy to learn and customizable to fit your application’s needs. Closure Templates support JavaScript and Java and use a data model and expression syntax that works for either language. You can also use the built-in message support to easily localize your applications.

Javascript-techniques-46 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Useful jQuery Plugins

TipTip jQuery Plugin
TipTip detects the edges of the browser window and will make sure the tooltip stays within the current window size. As a result the tooltip will adjust itself to be displayed above, below, to the left or to the right of the element with TipTip applied to it, depending on what is necessary to stay within the browser window. TipTip is a very lightweight and intelligent custom tooltip jQuery plugin. It uses ZERO images and is completely customizable via CSS. It’s also only 3.5kb minified!

Javascript-techniques-65 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jQuery Roundabout
Roundabout is a jQuery plugin that converts a structure of static HTML elements into a highly customizable turntable-like interactive area. (And now, not just turntables, but many shapes!)

Javascript-techniques-69 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jParse – jQuery XML Parse Plugin
jParse is a jQuery plugin that allows you to parse XML that was fetched with the jQuery .ajax method (making it fully customizable).

Javascript-techniques-72 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jQuery Quicksand plugin
Reorder and filter items with a nice shuffling animation.

Javascript-techniques-48 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

typeQuery, change website typography with jquery
typeQuery gives the flexibility to change the font-family for everything you define with class, id, or tag, this example is referring to the selected item on a select object with id=”tag” and the font-family value at select object with id=”family”: $($("#tag").val()).css("font-family", $("#family").val());

Javascript-techniques-70 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Flip! A jQuery plugin v0.9.9
Flip is a jQuery plugin that will flip easily your elements in four directions.

Javascript-techniques-55 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Data Encryption With JavaScript: jCryption
jCryption is a jQuery plugin for encrypting POST/GET data submitted by forms. It uses public-key algorithm of RSA for the encryption & has a PHP file for handling the decryption of data.

Javascript-techniques-24 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Minimalist jQuery: 11 useful plugins under 4K
jQuery makes our lives easier. So much so that it’s tempting to use it all the time, inadvertently slowing our page load times (cue YSlow and Hammerhead). Combining, compressing, and delivering scripts at the end of your page helps in the HTTP request department. On the file size front, below are jQuery plugins that give solid bang for your performance buck.

Javascript-techniques-79 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Undo/Redo in jQuery
An easy-to-use plugin for adding undo/redo capabilities to a jQuery application. It is based loosely on the Objective-C/Cocoa way of doing things.

Javascript-techniques-81 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

editease
editEase – jQuery CMS | no fuss, no database, no worries

Javascript-techniques-78 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jsHub
jsHub is a single piece of JavaScript (a “tag”) that can handle reading different sorts of page information and then send them to many different vendors’ products. One piece of code to send to Google Analytics, Omniture SiteCatalyst, WebTrends and Mixpanel. Instead of one piece of JavaScript per vendor, jsHub has a single piece of code (the “hub”) and plugins that know how to translate into the required wire protocol for each vendor. Vendors only maintain the plugin for their product.

Javascript-techniques-22 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Educational JavaScript Resources and Tutorials

Caffeinated Simpleton
JavaScript is an amazing little language, but it’s got some quirks that turn a lot of people off. One of those quirks is this, and how it’s not necessarily what you expect it to be. this isn’t that complicated, but there are very few explanations of how it works on the internet. This article is an attempt to explain how this works and how to use it properly.

Javascript-techniques-07 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

What You Need To Know About JavaScript Scope
This article discusses how JavaScript handles scope and how various JavaScript libraries provide methods for dealing with it and how they smooth out a few bumps. We’ll also look at how you can get back to basics and do some interesting scope wrangling without a library, a useful approach if you’re writing code that needs to stand alone.

Javascript-techniques-25 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Learning Advanced JavaScript
A very nice tutorial to learn JavaScript, containing code and discussion from the upcoming book Secrets of the JavaScript Ninja by John Resig.

Javascript-techniques-30 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Highlight search terms automagically with JavaScript and mark
Script surrounding the search term(s) with the mark element rather than a span, although the class searchword is retained in case you want to style these marks differently from others. In the CSS, the rule article mark is just added to turn it a gentle shade of pink.

10 Really Helpful Traversing Functions in jQuery
With jQuery, selecting HTML elements is laughably easy. But at times, we may wish to further refine the selection, which can be a hassle when the HTML structure is complicated. In this tutorial, we’ll explore ten ways that we can refine and extend a set of wrapped elements that we wish to operate upon.

Javascript-techniques-74 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Using keyboard shortcuts in Javascript
If you want to enhance your web app, Javascript keyboards shortcuts is definitely something to consider. In this article, you’ll learn to use JS keyboard shortcuts, with and without the JQuery framework.

Javascript-techniques-29 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Code Conventions for the JavaScript Programming Language
This is a set of coding conventions and rules for use in JavaScript programming.

Javascript-techniques-31 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

jQuery – Select element cheat sheet
This cheat sheet helps you to find the index of a selected option, set the selected option by value, set the selected option by text, insert a new option before or after another and get the text or value of the selected option.

Javascript-techniques-76 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Compare JavaScript frameworks
Modern Web sites and Web applications tend to rely quite heavily on client-side JavaScript to provide rich interactivity, particularly through the advent of asynchronous HTTP requests that do not require page refreshes to return data or responses from a server-side script or database system. In this article, you will discover how JavaScript frameworks make it easier and faster to create highly interactive and responsive Web sites and Web applications.

Javascript-techniques-77 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Park your Horse, Code Cowboy: Professional JavaScript Workflows, Part 1
In this series, we’ll talk about tools & techniques you can use to cover those No’s, and cut a lot of strife & embarrassment from your JavaScript experience.

Javascript-techniques-47 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

JavaScript Reference examples (example source code)
JavaScript Reference examples, organized by Objects, Properties, Methods & Collections. Some Event Handlers Reference are also available.

Javascript-techniques-20 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

JavaScript best practices
A compilation of best practices and good advice I’ve amassed over the years, much of it learnt the hard way (experimentation and suchlike). Take the advice below to heart and keep it in a part of your brain that has a quick access route so you can apply it without thinking about it. I am sure you will find things to disagree with, and that is a good thing – you should question what you read, and strive to find better solutions. However, I have found that following these principles has made me a more effective developer and allowed other developers to build upon my work more easily.

Javascript-techniques-15 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

wtfjs
JavaScript is a language we love despite it giving us so much to hate. This is a collection of those very special irregularities, inconstancies and just plain painfully unintuitive moments for the language of the web.

Javascript-techniques-41 in 45 Fresh Useful JavaScript and jQuery Techniques and Tools

Related Posts

You may be interested in the following related posts:

Poll

What programming language should we cover in next round-up?surveys

© Smashing Editorial for Smashing Magazine, 2010. | Permalink | 63 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , ,

0
Your rating: None

By Tony White

Some of you may remember the days when 30KB was the recommended maximum size of a web page, a value which included HTML, CSS, JavaScript, Flash, and images. I find with every new project with even the slightest bit of complexity, it’s not long before that 30 KB ideal is well out of my reach. With the popularity of CSS layouts and JavaScript-enriched web page experiences, it’s not uncommon, particularly for large sites, for the CSS files alone to jump well beyond that 30KB ceiling.

But there are some principles to consider during and after you write your CSS to help keep it tight and optimized. Optimization isn’t just minimizing file size — it’s also about being organized, clutter-free, and efficient. You’ll find that the more knowledge you have about optimal CSS practices, smaller file size will inevitably come as an direct result of their implementation. You may already be familiar with some of the principles mentioned below, but they are worth a review. Being familiar with this concepts will help you write optimized CSS code and make you a better all-around web designer.

1. Use Shorthand

If you’re not already writing in shorthand, you’re late to the party. But fortunately, this party never ends. Using shorthand properties is the single easiest practice you can do to cut down your code (and coding time). There’s no better time than the present to start this efficient coding practice, or to review it.

Margin, border, padding, background, font, list-style, and even outline are all properties that allow shorthand (and that’s not even an extensive list!).

CSS Shorthand means that instead of using different declarations for related properties…


p { margin-top: 10px;
	margin-right: 20px;
	margin-bottom:  30px;
	margin-left: 40px; }

… you may use shorthand properties to combine those values like so:

	p { margin: 10px 20px 30px 40px; }

By specifying a different number of values, browsers would interpret the rules in a specified manner, illustrated in the diagram below.

Illustration of how shorthand declarations are interpreted depending on how many values are specified for a property
Illustration of how shorthand declarations are interpreted depending on how many values are specified for a property. This order also applies to padding and border-width among other properties.

Font is another helpful shorthand property that helps save some room and keystrokes.

Illustration of font shorthand examples
Examples of the font shorthand property. Note: leaving some values unspecified will mean that those properties will reset to thier initial values.

Those are just two examples of shorthand, but by no means should be considered a comprehensive guide. Even if you are familiar with the rules above, be sure to look at the articles mentioned below for more helpful reminders of those powerful properties that help keep your code succinct. Because of the number of lines and characters saved, going from a previous version of a CSS file which used no shorthand properties to one that makes full use of shorthand can have dramatic effect on file size.

See CSS Shorthand Guide (dustindiaz.com) and Efficient CSS with shorthand properties (456bereastreet.com) for more information about shorthand properties.

2. Axe the Hacks

Jon Hick's blog hicksdesign.co.uk/journal makes use of conditional comments
Jon Hick’s blog hicksdesign.co.uk/journal makes use of conditional comments

Hacks against dead browsers are safe, but hacks against the living aren’t. None of them. Ever.

Keep CSS Simple - Peter-Paul Koch (digitial-web.com)

If you’re like me, those words from Peter-Paul Koch’s nearly 5-year-old article may make you feel a little embarrased. After all, who hasn’t served hacks to Internet Explorer 6 and even Internet Explorer 7? As bad as we may want IE6 to lay six pixels under, the truth is it’s far from dead.

But now we know that using conditional comments to serve hacks correctional declarations for IE6 and IE7 is an accepted practice, even recommended by the Microsoft IE development team. Using conditional comments to serve IE-specific CSS rules has the added benefit of serving a cleaner, and therefore smaller, default CSS file to more standards-compliant browsers, while only those browsers that need the hackery daiquri (i.e. IE) will download the additional page weight.

Here’s how to use conditional comments to serve styles only to Internet Explorer 6:


	<!--[if IE 6]>
		<link rel="stylesheet" type="text/css" href="ie6.css">
	<![endif]-->

For IE7, you can use the above and substitute “6″ for “7″.

Alternatively, if there is hack-less way of getting the desired result using CSS, with all other things being equal, go for it! The less hacks you have to write, the simpler and lighter the code.

3. Use whitespace wisely

Whitespace, including spaces, tabs, and extra line breaks, is important for readability for CSS code. However, whitespace does add, however miniscule it may be, to page weight. Every space, line-break, and tab you can eliminate is like having one less character.

But this is one area where I would not encourage you to skimp just to get a smaller file. It’s still important that you write in a way that is readable to you (and hopefully to others), and if that includes using whitespace for formatting, so be it. After all, if you can’t read it, you’re going to have a hard time applying the other principles mentioned in this article. Just be aware of the fact that whitespace is like air - you might not be able to see it, but it does weigh something.

The figure below shows two different extremes in formatting style, with much whitespace, and the other with very little. I happen to favor the single-line formatting option without tabs, as I can scan the selectors a little easier, and I develop using the full width of my wide-screen monitor. But that’s just me. You may like your selectors to appear nested, and your declarations on each line.

Illustration of two extremes in CSS formatting, one with lots of whitespace, one with little whitespace
Illustration of two extremes in CSS formatting: lots of whitespace vs. very little whitespace

Using whitespace effectively is great, and a recommended practice for easy-to-manage code, but be aware that the less whitespace you have, the smaller the file. Even if you choose work with whitespace with your working file, you can choose to remove it for the production version of your CSS file, so your files stay skinny where it really counts.

4. Prune frameworks and resets

Nathan Smith's 960 Grid System uses a reset
Nathan Smith’s 960 Grid System CSS framework uses a reset rule.

If you’ve chosen to use a CSS framework (including ones you’ve written yourself), take the time to review the documentation as well as every line of the CSS file. You may find that the framework includes some rules that you don’t care to use for your current project, and they can be weeded out. Also, you may find that the framework includes a more elegant and concise way of achieving a presentational detail than what you normally use, and knowing about them can help prevent you duplicating rule sets unintentionally.

This goes for resets as well. YUI Grid CSS uses a reset, and Eric Meyer’s Reset is also very popular. Resets are great to use because they help to neutralize a browser’s default style. But if you know the nature of the site you are building, you may find some declarations that you know you’ll never need. <pre> and <code> will likely go unused on my Aunt Martha’s recipe blog. A design portfolio probably won’t ever use <sub>, <dfn>, <var>, etc. So ditch what you don’t need. It’s not only ok, it’s encouraged, even by Eric Meyer:

As I say on the reset page, those styles aren’t supposed to be left alone by anyone. They’re a starting point.

Crafting Ourselves - Eric Meyer (meyerweb.com)

Using a framework and/or a reset set of rules can help keep your work optimized, but they should not be accepted in their default state. Considering each declaration and cutting back on unneccessary ones can further help you keep your CSS files lean and readable.

5. Future-proof your CSS

Doug Bowman's stopdesign.com CSS reveals specially crafted selectors used for layout
Doug Bowman’s stopdesign.com CSS reveals specially crafted selectors used for layout.

Another way to optimize your code is to separate layout-specific declarations from the rest of your rules. I’ve heard options of separating typography and colors from layout-specific rules in the CSS file. I’ve never been fond of this practice, as I don’t care to repeat selectors just because I have different types of declarations to associate with them.

However, I’m warming up to the idea of separating layout styles from the rest of the styles, and giving layout it’s own file, or at least it’s own section. This is also advocated in Andy Clarke’s Transcending CSS. Within the book, Clarke reminds us of the following:

Full CSS layouts have always been a compromise. The current CSS specifications were never designed to create the visually rich and complex interface layouts that modern Web demands. The current methods — floats and positioning — were never intended as layout tools.

Transcending CSS - Andy Clarke.

One way of interpreting this is that floats and positions to establish sidebars and columns are, well, layout hacks. And though we really don’t have an alternative, we hopefully will once a layout standard is agreed upon and browsers start supporting them. When that happens, it should be easy to swap out those hacked up box-model properties for ones intended for layout. Though it will be a while before new layout modules are here, using the right properties to handle layout instead of compensating for the quirks of our current limited set of properties will most certainly help condense page weight.

6. Document your work

David Shea's markup guide at mezzoblue.com
David Shea’s markup guide illustrates the proper usage for HTML tags and how those are represented on his site, mezzoblue.com. Even sites without dynamic HTML can have this simple and effective guide (using its own CSS file, of course!) as a starting point of documentation.

For a team of designers, it is extremely important to communicate regularly so that markup and style rules are created in a consistent way, and also to create site standards. For example, if someone comes up with way to markup a tab interface for the site, documentation will keep others from duplicating that effort, preventing code bloat in the HTML and CSS.

Documentation, including markup guides and style sheet guides, is not just for group efforts — they are just as important for a one-man design team. After all, a year after working on other things, revisiting one of your own projects can feel quite foreign. Your future self might appreciate reminder of how your CSS grid framework is supposed to work, or what pages already have a treatment for a secondary action form button, and it will save you or someone else from appending redundant and unnecessary rules to your CSS.

The choice to use documentation has a bonus side effect of being a great place to park explanations that otherwise must be included as CSS comments. CSS comments are great for sectioning off chunks of long CSS files, but verbose comments that are used to explain design choices can add to file size, and might be better suited to a markup and style guide. Documenting your code using CSS comments within your working file is most definitely better than nothing at all, but housing that material in separate documentation is a great way to keep the code focus and free from bloat.

7. Make use of compression

Some great applications have been created to compress and optimize CSS for you, allowing you to serve a human-unreadable but still browser-friendly files that are a fraction of the origional working copies. Applications like CSSTidy and the YUI Compressor can compress whitespace, detect and correct for CSS properties that are overwrite each other, and look for opportunites to use CSS shorthand that you may have missed. (These types of applications are excellent sources to read about, if for no other reason, to learn what things you can further do by hand).

Even popular text editors like BBEdit, TextMate, and TopStyle, can help format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS Tools.

It is important to note that these applications do their best to minimize errors, but they aren’t always perfect. Also, they work best when browser hacks are not included in the file set (which is yet another reason to keep those hacks external).

There is one last type of application that can help prune CSS file size I’d like to mention. It can crawl a web site and log which CSS rules and declarations are not being applied, then bring these to your attention. Unfortunately, this tool hasn’t been inventend yet, but I would gladly pay for such a application.

I can recall times when I’ve been afraid to delete certain rules because there is no documentation that explains to me that those selectors are leftover from previous iterations of development. If an app can bring those rules to my attention, that will help with maintenance and keeping CSS files lean.

Conclusion

Clean and optimized code is important not just for file size, but for maintenance and readability as well. The principles mentioned above are good considerations not just for CSS, but can be applied to HTML, JavaScript, and other programming languages. CSS files are not as prominent as the rendering of your web site to an end-user, but consideration of the above principles can help with both the user experience (in the form of smaller file sizes) and the developer experience (cleaner code). Apply these principles to your current and future projects, and and you will surely appreciate the efforts.

About the author

Tony White runs the one-man show Ask the CSS Guy, an after-hours blog devoted to peaking under the hood of CSS and JavaScript web-design techniques, as well as troubleshooting CSS-related problems. He resides in Memphis, Tennessee.

0
Your rating: None