The Smashing Book – The Art and Science of CSS-Layouts (part 2 of 2)

← The Art and Science of CSS-Layouts (1/1)TOC

Fluid Grid Layouts

Grid-based design is a manifestation of order and precision. Essentially, grids allow for a strategic and systematic organization of typography and design elements, using alignment, symmetry and proper spacing; they contribute to creating designs that are pleasing to read and easy to scan. Grid layouts can be implemented in various layout types, but designers often assume that flexible layouts in particular are difficult or impossible to pair with traditional grid systems. That is not necessarily the case.

Essentially, a fluid grid layout can be created through a smart use of DIV layers, percentages and very simple math. The idea comes from Ethan Marcotte (Fluid Grids, www.alistapart.com), who realized that “if we could treat font sizes not as pixels, but as proportions measured against their container, we could do the same with the different elements draped across our grid”. His basic idea is to use relative units, namely percentages, and a simple division formula to find the equivalents of pixel widths that would normally be used for fixed-width design. Because em units in typography are all about context, other elements in the overall layout could be considered the same. As Ethan points out, “this will allow us to convert our design’s pixel-based widths into percentages, and keep the proportions of our grid intact as it resizes”.

A classic way to calculate proportion is to divide the font size of a given element in pixels by the font size of its container (that is, its context). As a result, we get the desired proportion, expressed in relative, em- or percentage-friendly terms. We get a quite obvious yet very helpful formula: target ÷ context = result.

Now, if we apply this formula to a design, we should end up with a solid fluid layout. However, we actually want a grid layout, so we start out by creating a well-defined fixed-width grid with seven columns of 124 pixels each, separated by 20 pixel-wide gutters, all of which adds up to a width of 988 pixels.

Let’s assume now that we have a 700 pixel-width <h1> element in our layout (which spans five columns and four gutters between them: 5 * 124 pixels + 4 * 20 pixels = 700 pixels). This element should be a block element and should be centered in the layout (which means having the overall horizontal margin of 288 pixels, 144 pixels on the left side and 144 pixels on the right side).

To calculate the width of <h1> in relative units, we simply divide 700 pixels (the target) by 988 pixels (the context), giving us 700 ÷ 988 = 0.7085. 0.7085 translates to 70.85%, which we can put directly in our style sheet:

h1 { 
width: 70.85%; /* 700px / 988px = 0.7085 */ 
} 

Of course, we also need to take care of the margins. Because the left margin is supposed to be 144 pixels (the target), we can again apply our formula to derive its relative width in the container (the context): 144 ÷ 988 = 0.14575, which translates to 14.575%. Finally, we get:

h1 { 
margin-left: 14.575%; /* 144px / 988px = 0.14575 */ 
width: 70.85%; /* 700px / 988px = 0.7085 */ 
} 

ala-grid.png
A simple grid layout with a title, information and large content block.

What remains is to apply this formula the same way to all layout elements, and we will end up with a solid, flexible, fluid grid. This is a very easy -concept and a much more efficient way to handle proportions in fluid -design. With this technique, a designer doesn’t have the excuse that proportions can-not be maintained or that they ruin the aesthetic appeal of their layouts.

Designers determine the length of margins in different ways. One way is to calculate the percentages of the margins (in this case, 20 pixels ÷ 880 pixels). Another is to set fixed margins or, as in our example, hard-code them as 20 pixels.

Each method has its pros and cons. With percentage margins, the designer risks making the margins too wide in very large screen resolutions but probably achieves better proportion. Fixed margins may cause slight imperfections in the proportions but guarantee that the spacing will look right no matter what the screen size is.

Adaptive Fluid (Liquid) Layouts

A common problem with fluid designs is that, even though they adapt to many screen resolutions, if the resolution is too small (such as on a phone or PDA) or incredibly large, things start to look a bit funny. For example, a three-column layout would look very cluttered on a PDA screen whose resolution is only 240 pixels wide. On the other hand, if the “min-width” property is used, the layout may contain a horizontal scroll bar and look unreadable.

To address this problem, we can use a technique that involves adapting content to specific ranges of screen resolutions. This is where the name “adaptive fluid layout” comes from. We can create slightly different custom layouts for resolutions that are 640 to 800 pixels, 320 to 640 pixels, 240 to 320 pixels and 240 pixels and below, respectively. Likewise, custom adjustments could be made for screen resolutions that are 800 to 1024 pixels, 1024 to 1280 pixels and 1280 pixels and up, respectively.

The benefits are obvious: the designer is able to leverage a layout’s look at different resolutions with greater accuracy. The tiniest and largest resolutions can be handled perfectly, while better adhering to design principles of spacing and balance, no matter what platform the design is being viewed on.

To create this type of layout, we need two things: separate style sheets for every range of screen resolutions, and a way of determining a user’s screen resolution. The first step is to create a set of alternative layout files. For example, one file could be called narrow.css and would be tailored to very narrow resolutions. Another could be normal.css and would apply to conventional computer screen resolutions, and a third could be wide.css and would handle unusually large resolutions.

We can then use JavaScript to make some simple alterations depending on the preset style sheets: for example, using Kevin Hale’s “Dynamic Resolution-Dependent Layout Technique” (www.particletree.com) or Marc Van Den Dobblesteen’s “Switchy McLayout” (www.alistapart.com). Declarations of all the style sheets and the JavaScript file are then put in the header, just like in any other type of layout.

<!-- Narrow style sheet --> 
<link rel="alternate stylesheet" type="text/css" href="css/ narrow.css" title="narrow" /> 
<!-- Default style sheet --> 
<link rel="stylesheet" type="text/css" href="css/normal.css" title="default" /> 
<!-- Wide style sheet --> 
<link rel="alternate stylesheet" type="text/css" href="css/wide.css" title="wide" /> 
<!-- Included JavaScript to switch style sheets --> 
<script src="scripts/dynamiclayout.js" type="text/ javascript"></script> 

Notice the title attribute in all three links to the style sheets: “narrow”, “default” and “wide”. Taking a closer look at the DynamicLayout() function in the JavaScript source, we can see that it is quite easy to customize which style sheet is called according to each title attribute. We can also see how to change the pixel widths accordingly.

function dynamicLayout(){ 
var browserWidth = getBrowserWidth(); 
// Narrow CSS rules 
if (browserWidth < 640) 
changeLayout("narrow") 
} 
// Normal (default) CSS rules 
if ((browserWidth >= 640) && (browserWidth <= 960))} 
changeLayout("default"); 
} 
// Wide CSS rules 
if (browserWidth > 960){ 
changeLayout("wide"); 
} 
} 

clagnut-new.png
Richard Rutter’s variable fixed-width layout uses JavaScript to automatically scale the layout, including the typography, on the fly. Viewed at 1280 pixels, the layout is a four-column layout, but shrunk down to 850 pixels (as seen in the view port), the layout automatically becomes a three-column layout, with the fourth-column shifting down.

switchy-mclayout.png
In the above image, you can see a demonstration of Switchy McLayout viewed at different Web browser sizes. The layout automatically adjusts as you resize the browser.

Notice that because adaptive fluid layouts rely on JavaScript, they require users to have JavaScript enabled so that it can detect the monitor’s resolution and serve the appropriate style sheet.

“Variable fixed-width layout” is a similar technique developed by Richard Rutter, based on Simon Collison’s width-based layout (which he discusses in the article “Redesign Notes 1: Width-Based Layout”, colly.com). As the screen resizes, so does the layout and typography. The change in layout size happens in real time, so if you were to resize your Web browser, the layout would adapt to your new size.

As pointed out above, a common problem with fluid layouts is that the text gets either so stretched or squished that the layout loses readability. Very narrow screens seem to create the biggest problem by causing big gaps in the text, but either extreme can frustrate users equally. Max-width and min-width are possible solutions, but when these properties are applied, the layout simply reverts to a partially fixed-width layout, and we lose the overall flexibility. Tinned Fruit’s text-zooming technique (tinnedfruit.com) is based on a JavaScript that automatically resizes text based on the width of the user’s screen. As the screen gets wider, the text gets larger. Likewise, as the screen gets thinner, the text gets smaller. In addition to this basic functionality, a designer can set a maximum and minimum text size so that the user never sees any odd-sized text. Furthermore, the designer can choose which elements should and should not be affected by the text zoom.

You can add the text-zooming JavaScript to a Web page externally. Below the external script line, simply insert the following code, modified as necessary:

<script type="text/javascript"> 
var contentZoom = new TextZoom( 
"Content", // Reference element 
"Content", // Target element 
0.22, // Zoom ratio 
70, // Minimum font size (%) 
130); // Maximum font size (%) 
addLoadEvent(textZoomInit); 
</script> 

text-zoom-large.png
Text-zoom technique: here is a portion of the maximized page (large width) that displays larger text.

text-zoom-small.png
Text-zoom technique: the same page as above, except minimized to about 700 pixels in width. The text is resized along with the browser. Notice that the text in the navigation at the top is not resized.

A similar technique was suggested by Soh Tanaka in his article “Smart Columns with CSS and jQuery” (www.sohtanaka.com). The technique is based on a script that alters the width of DIVs for the best viewing experience, and it also determines how many columns can be viewed across the page in the browser’s current size. The script removes any left-over white space from the ends of columns (which may have been caused by the browser’s width) and then redistributes it evenly throughout the columns using jQuery. The technique is perfect for users who resize their browsers, and does not simply treat browsers indiscriminately: a good example of an adaptive fluid layout.

Elastic (Zoomable) Layouts

When viewing a website with a fluid layout, the content can get so wide that the text becomes difficult to read. To improve readability, designers tend to limit the maximum width of a layout using CSS properties. An elastic (or zoomable) layout is a different approach that achieves the same goal; the basic idea is that designers adjust the width of the layout based on the user’s font size rather than the browser’s view port.

A pixel is an unscalable dot on a computer screen, whereas an em is a square unit of font size. Font sizes vary, and the em is a relative unit that adjusts to users’ text-size preferences (Elastic Design, www.alistapart.com). Consequently, designers size fonts in em units relative to the font-size value of their parent elements. By using ems for both layout blocks and text elements, designers are able to make a Web layout scale consistently, maintain optimal line length for the body copy and create realistic zoom effects. The result: when the user increases the font size, the layout stretches automatically, just as you would expect from an elastic object.

Because the layout width doesn’t depend on the browser’s view port, elastic layouts behave similarly to fixed-width layouts, and they also inherit their advantages and disadvantages. A major increase in the browser’s font size can make the layout explode in width and height, making the page completely unusable and unreadable. However, this will rarely happen, because a three-time increase in font size is not very common (especially if the designer uses a large enough font size as the base line for text elements).

As with fluid layouts, one of the most difficult things to grasp when starting out with elastic layouts is the math involved in calculating the proper em values. To simplify the conversion from pixels to ems, you can set the base value of the body’s font size to 0.625 em, or 62.5% (because the default font size of most browsers is 16 pixels1, and 10 pixels is exactly 62.5% of 16 pixels), which comes out to 10 pixels, making the calculation of the font size of child elements easier. For example, by setting the font size in the main body area to 0.625 em, you can set a DIV container that should be 960 pixels in width to 96 em; and so a <p> element there whose font size would otherwise be 12 pixels would now be 1.2 em.

One issue with elastic layouts, or layouts whose widths are adjusted based on font sizes, is the presentation of multimedia content, such as images and Flash objects. This adds complexity to elastic layouts, because in order for all elements in the layout to maintain their proportion, they must scale as the font size increases. Elastic layouts sometimes allow for all of their elements to scale; in other words, images will scale up or down in proportion to the layout, depending on the user’s settings.

Of course, this can be done by giving images percentage-based width and height property values, such as <img width="80%" height="80%" alt="Image" />. Remember, though, that scaling up images with very small resolutions using percentage values will decrease their quality, because the browser would perform a “simulated” zoom, resulting in pixellated and blurry images. Besides, the browser would load the entire (large) images from the server and rescale them, thus increasing the server load and delaying the page loading time. Therefore, most designers always use absolute pixel values for images.

Another solution, described in Harvey Kane’s article “Automatic Magazine Layout” (www.alistapart.com) requires some math and PHP. The title derives from how images are displayed in magazines: organized and always perfectly aligned. Consider the following PHP script:

# include the class file 
require_once('magazinelayout.class.php'); 
# Define the width for the output area (pixels) 
$width = 600; 
# Define padding around each image; this *must* be included 
# in your style sheet (pixels) 
$padding = 3; 
# Define your template for outputting images 
# (Don’t forget to escape the &) 
$template = '<img src="image.php?size=[size]&file=[image]" 
alt="Screenshot" />'; 
# create a new instance of the class 
$mag = new magazinelayout($width,$padding,$template); 
# Add the images in any order 
$mag->addImage( 'landscape1.jpg' ); 
$mag->addImage( 'portrait1.jpg' ); 
$mag->addImage( 'landscape2.jpg' ); 
# display the output 
echo $mag->getHtml(); 

We can pre-define the width that we’d like our entire magazine-inspired image layout to render as. So, if we can determine the user’s browser width, we can figure out how wide our image layout should be. This is easy enough, because we’ve already done it with our second technique: Fluid layouts with adaptive content. In his script, Kevin Hale uses a method called getBrowserWidth(). You can get an in-depth look at the code for this method in his article.

If we can use this method to retrieve the browser’s width as a number, then we can use that number to find the pixel width of our content area (or whatever other area these images are going to be placed in). Let’s say we’d like to put the images in our content area, which is set to a 70% width. Using simple math, we just need to figure out how many pixels is 70% of the browser’s width.

Pixel width = Percentage of Content Area * Browser Width 
$width = 0.70 * getBrowserWidth(); 

This is, of course, pretty basic math, and it is a pretty basic solution for dealing with images in fluid layouts, once the initial PHP script is set up. Adjust the PHP script to automatically find the pixel width of the images, and you’ve got a great way of dealing with images, or any other content that has a set width, in a fluid layout.

The main advantage of the elastic layout is its ability to always keep the proportions of design elements, ensuring proper readability and positioning. Elastic layouts are often the first choice for designers who want a compromise between fluid and fixed designs; the pros of each are found in elastic layouts. However, this layout type is more difficult to implement, and a lot of savvy and testing is often needed to get the layout right for most users.

Let’s try a simple two-column elastic layout using the same HTML structure we used before. If we know that 1 em equals 16 pixels, then a width of 960 pixels equals 60 em. The left column at 600 pixels translates to 37.5 em, and the right column at 360 pixels translates to 22.5 em. To make it easier, here’s the formula for calculating widths: 1 em ÷ 16 px * (width in pixels) = em equivalent.

#container { 
width: 60em; 
} 
#header { 
width: 60em; 
} 
#leftCol { 
width: 37.5em; 
float: left; 
display: inline; /* IE 5/6 Doubled Float-Margin Bug */ 
} 
#rightCol { 
width: 22.5em; 
float: right; 
display: inline; /* IE 5/6 Doubled Float-Margin Bug */ 
} 
#footer { 
width: 60em; 
clear: both; } 

The design community is divided in a heated disagreement about the viability of flexible layouts. The new generation of Web browsers – Firefox 3+, Opera 9.5+ and Internet Explorer 7+ – comes with a feature that seems will save Web developers a lot of work in future, namely the full-page zoom.

Instead of simply increasing and decreasing the font size of a website, browsers now enable users to literally scale the rendered layout, including visuals and background images. The whole design layout is scaled proportionally according to a set zoom factor, with all elements of a page’s layout expanding equally. Consequently, every fixed pixel-based layout becomes “scalable”; content always remains within the layout area it is supposed to be in, and there is no chance of boxes overlapping each other, as we saw in previous generations of Web browsers. Intuitively, this leads to the conclusion that elastic layouts will become obsolete and will have outlived their purpose, because they achieve the same effect with counter-intuitive CSS code.

However, this is not true. As Zoe Mickley Gillenwater points out ( “Why Browser Zoom Shouldn’t Kill Flexible Layouts”, www.zomigi.com), if you offer users a fixed-width layout with page zoom, they will sometimes see different number of characters per line than what you intended (for example, some people may increase the size because of vision problems).

It is also harder to preserve design proportions, because variable text sizes make it hard to predict where content will be displayed on a fixed-width page. Besides, while page zoom increases (and decreases) the overall layout of the website, in some situations it doesn’t make sense to zoom in on a logo or icon. On the other hand, it may make sense to enable users to scale only the content area or certain layout elements, which would be impossible with the browser’s zoom. And of course, all of the shortcomings of the pixel-based layout, including the horizontal scroll bar and excessive white space, still hold. The bottom line is, page zoom is helpful for users, but it is not a silver bullet for developers.

Hybrid Layouts

In practice, designers usually try to come up with the right mix of fixed-width, liquid and elastic layout elements to offer users the advantages of each, while minimizing the shortcomings of each as much as possible.

For instance, it has become a common practice to use em units for the content area (thus ensuring optimal line length and text scaling in Internet Explorer 6) and pixel units for the sidebar (because the sidebar often contains fixed-size ad banners that make this solution sensible). Another related technique is to have a fluid content area with “min-width” and “max-width” CSS attributes instead of the elastic element, making it possible for users to adjust the line length of the content block according to their personal preferences.

Less popular, yet still interesting, is the Jello-liquid layout (“Jello: A Different Liquid Layout”, www.uwmike.com). This technique is intended to slow down the proportional growth of a flexible layout so that its content area doesn’t become unusable. So, a fluid layout that has a width of 960 pixels when viewed in a browser whose view port is 1024 * 768 (960 ÷ 1024 = 0.9375) would not have a width of 1350 pixels when viewed in a browser whose view port is 1440 * 900 (1440 ÷ 1350 = 0.9375), but would have a smaller width instead. To achieve this effect, a large portion of the layout is fixed using pixel units, while the rest is defined with percentage values relative to the view port’s width. The smaller the fixed portion of the layout, the better the layout stretches with the growing view port: simple and clever.

Another interesting approach is the fluid elastic layout, which combines both liquid and elastic elements. The idea here is to set “min-width” and “max-width” for an em-based layout in percentage units (in essence, giving you the ability to limit rescaling to a certain extent by taking into account the view port’s size). By setting maximum and minimum widths, the text scales to a certain point and then stops. The layout remains fluid because it automatically adapts to the user’s view port, yet it is also elastic because the width of the columns is “scaled” automatically when the browser window is resized or the font size changes.

In the following example, we set the “max-width” CSS property for the container and columns. This limits the scaling of the layout to 100% of the browser’s view port. Again, “max-width” is not supported in older versions of IE, so we have to implement a workaround for IE 6 and below (not shown in the following example).

#container { 
width: 60em; 
max-width: 100%; 
} 
#header { 
background-color: #cccccc; 
width:60em; 
max-width:100%; 
} 
#leftCol { 
width:37.5em; 
float:left; 
display: inline; /* IE 5/6 Doubled Float-Margin Bug */ 
max-width:62.5%; 
} 
#rightCol { 
width:22.5em; 
float:right; 
max-width:37.5%; 
} 
#footer { 
width:60em; 
max-width:100%; 
clear:both; 
} 

Which Layout Is Right For Your Website?

The question of optimal layout doesn’t have a single answer. Depending on the context, time constraints and designer’s skills, each layout type has its purpose. A fixed-width approach usually works best for advanced visual layouts with heavy graphics (such as for entertainment, promotional and Flash-based websites, but sometimes also portfolios) because the images can be positioned more precisely, resulting in a more predictable and less error-prone design. Designers of such layouts need to consider the profile of the average user to make sure that the layout’s width is not too narrow or wide but remains usable across various browser view ports. Coding fixed-width layouts is also more straightforward and intuitive, as one doesn’t need to consider the relationship and proportions between elements.

While some designers strive for cross-browser pixel perfection, proponents of fluid designs do not think that layouts have to look identical across all platforms and screen resolutions. If this reflects your point of view, you may want to consider fluid layouts for your designs. These layouts are more time-consuming and less straightforward to develop, and they can create a risky and unpredictable environment, but they allow users to adjust layouts to their personal preferences. Liquid layouts usually have higher production costs but significantly lower maintenance costs than fixed-width layouts, and so provide a solid foundation for flexible, cross-resolution websites. Designers need to make sure that content blocks have the proper line length and should use the “min-width” and max-width“ CSS properties if necessary.

Still can’t decide? An elastic or partially elastic design is another option. When implemented correctly, elastic layouts bring a more predictable yet still flexible quality to layouts. Because elastic elements depend on font size (and not the browser’s view port), they allow designers to “freeze” proportions between layout blocks, ensuring balance between elements and good readability. In particular, because optimal readability (while also important in fixed-width layouts) is more critical on text-heavy websites, flexible layouts are more often used for magazines, online shops, blogs and the like. A smart use of the fluid grid can create an adaptable layout whose proportions remain faithful to the classic rules of graphic design.

In practice, designers often create an elastic layout when they use ems for typography and containers and a smart mix of percentages and pixel widths for the rest of the layout elements. These and similar hybrid layouts are most widely used in practice, reflecting designers’ attempts to find the best solution for each situation.

To conclude, it’s worth mentioning that with mobile phones, netbooks and game consoles becoming viable alternatives for Web browsing, smaller (and also bigger) resolutions are becoming more important and need to be carefully considered. For such platforms, dynamic resolution-dependent techniques may turn out to be useful and even necessary extensions to your layout type of choice. Adaptive layouts, though requiring more time to create, can handle unusually small or large screen resolutions with a bit of manual customization, helping the designer deliver the most preferred results to the most users. With the growing variety of screen widths, it’s only a matter of time before these techniques become essential.

  1. 16 pixels is a widely adopted default browser font size, but some people may change it or have the dpi on their machines set to 120 instead of 96, which would make all of the text on their system bigger.

← The Art and Science of CSS-Layouts (1/1)TOC

The Smashing Editorial loves high-quality content and cares about little details. We also believe that content and design are crafts worth sharpening.

  1. 00

    No comments have been posted yet. Please feel free to comment first!
    Note: Make sure your comment is related to the topic of the article above. Let's start a personal and meaningful conversation!

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top