Tuesday, June 09, 2009

CSS Café Tutorial 14 - Horses for Courses and Margins for Gutters

Our project now has two side by side columns, the #specials floating to the right and #intro and #coffee on the left. Although when you look at the greyed out image, the columns are running into each other and would definitely benefit from additional space. I am going to add some space or what's called a gutter in between the columns to separate them. We know that the width of #specials div is 270 pixels. If I make the right margins of #intro and #coffee slightly larger than 270, the difference will make up the gutter space in between.

#intro, #coffee { margin-right: 330px; }



Here's the document to view in your browser; the spacing looks much better. Resize the page, the space between the columns will stay the same.

Wait you might say, I see a problem with your drawing. I thought margins are spaces between elements or their containing block. Your drawing shows a right margin going all the way to the browser window, completely bypassing the #specials div which is an element.

Of course, you'd be right thinking that except that #specials is a float and thus no longer in the normal flow. The browser acts as if #specials does not exist. Therefore it will calculate the right margin for #intro with respect to the edge of the browser window and not the #specials div.

Since we gave the float a width, you might also think if we did the same with #intro and #coffee divs we may be able to separate them without having to add a right margin. That approach does not work because when you resize your browser the space in between the two columns widen instead of staying the same. Let's actually give the two divs on the left a permanent width: #intro, #coffee { width: 500px; } and watch what happens when you resize browser window. After a certain point, the design breaks.

An important note on this approach: When you decrease the browser window, the divs on the left (intro and coffee) will be squeezed out of sight but don't think that they are disappearing. If we turn our debugging lines back on, you'll see that the block elements, #intro and #coffee do indeed take their space on the page (see the pink rectangles). #specials div is framed by a thin black border, and has a transparent background.

It's their inline content that shrinks back and start flowing around #specials div. The widths of #intro and #coffee stay constant at 500 pixels without ever changing. Their height will increase as the text wraps around when the floating #specials div moves into their territory which is normal behaviour for block elements. So it's the large space that forms between the columns that makes this approach unsuitable, otherwise, everything is behaving the way that they should.

Post a Comment