Understanding and Unleashing the Power of CSS Layouts
Author: Morten Rand-Hendriksen, Creative Director, Pink & Yellow Media
subscribe now to get yours.
In the last few years CSS layouts have become a must-have tool in the toolbox of web designers worldwide. Not only are they easy to maintain and update, but they also make the web a better place for people who, for one reason or another, don’t have or don’t use the latest and greatest in web browsing technology.
If we go back in time, the most common way of creating more advanced web page layout was tables. This was done more out of a lack of any better tool than anything else; but the custom stuck, and soon the web was littered with great-looking sites that had nightmarish HTML markup you would need a CIA decoder to figure out. As a consequence, although the sites looked great for the average user on a normal browser, users on slower or outdated browsers, on text-only browsers or those with disabilities who use text-to-speech or other non-visual browsers were presented with messy and unreadable pages.
As the need for better accessibility and more advanced web sites grew, designers and developers started migrating away from table-based layouts and toward Cascading Style Sheets (CSS). This layout tool had many advantages over tables, most notably that the styling and layout code was kept separate from the markup, often in entirely separate files. As a result, one CSS document could contain the styling for multiple HTML pages, and with that the designer now had the power to change the layout and style of multiple pages by changing the code in just one file.
With the explosive growth of blogs and other social media tools, CSS was finally brought to the forefront as the tool of choice for designers and developers, and its versatility has even taken it out of the classic web design world and into regular programming. It may surprise you to learn that many software applications like the popular Firefox browser use CSS as the basis for their appearance, giving the end user control of the user interface.
In spite of the immense popularity of CSS as a styling and layout code language, it remains notoriously illusive and poorly understood, and even seasoned designers and developers often find themselves scratching their heads when it comes to building pure CSS based layouts and sites that work properly. One of the main questions that keeps coming up again and again from novices as well as professionals is how to create basic CSS page layouts that work.
Then along came Expression Web 2—an application built to simplify the CSS authoring process and create 100% standards-based HTML and CSS. With this application you can build advanced and functional CSS layouts and styles without ever writing a single line of code, and with only limited understanding of what goes on behind the scenes. Out of the box, Expression Web 2 offers a series of preconfigured CSS layouts, but using them as a foundation means you never really understand what is going on and how the code works. It’s much better to build something from scratch.
In this tutorial you will learn how to build the three most common CSS layouts using the CSS tools found in Expression Web 2. These are the fluid width layout, the left-aligned fixed-width layout and the centered layout. You can see the final results on my
sample page. You will learn how to apply all of these layouts to the same HTML document without making any changes to the markup, and how to make variations of the different layouts in a few simple steps. In the end you will have a firm understanding of the basics of CSS layouts and also have the foundation on which to build solid CSS-based web pages.
As I explained in the (very long) intro to this tutorial, one of the advantages of CSS is that it separates the styling code from the actual content of the page, leaving the HTML markup nice and uncluttered and easy for text-only browsers to read. To save some time, I’ve created a standard HTML page with all the markup you’ll need for this tutorial.
The first step of this tutorial is to create a new site and import the HTML markup into Expression Web 2:
- Open Expression Web 2, click File > New > Web Site and select Empty Web Site from the menu. Save the new project under a new folder called CSS Layouts where you normally save your Expression Web 2 projects.
- Click File > Open and paste the web address to the unstyled HTML document (
http://pinkandyellow.com/tutorials/CSSlayouts/unstyled.html) into the File Name box. This opens the web page directly inside Expression Web 2 (see Figure 1).
Figure 1. Opening the unstyled document in Expression Web 2
- Click File > Save As and save the page as index.html under the folder you just created in step 1.
Sidebar: CSS and HTML—A Crash Course
Inspecting the page in Code View, you will see that I’ve inserted a series of code tags called “div” that look like this:
<div id="container"> <!-- Wraps all the content on the page -->
(... content ...)
These are the “boxes” that contain all the content in the page. The <div> is a box that is treated as a “block” meaning it breaks the line and is placed by itself on its own line. In contrast, the <span> is an inline box that does not break the line but stays adjacent to the rest of the content.
When I say “box” I literally mean a box. Whenever you place content inside a beginning and an end tag like this:
the browser draws an invisible box around it. If you use CSS to give that tag a background colour or a border, it will be constrained to the borders of that box.
In the page you just opened, there are a series of <div> tags or boxes within boxes. These contain different page elements and will be used to create the layout. Basically, we are going to define the size and shape of each box and tell the browser where to put them in relation to each other.
If we took out most of the text content, the page markup would look like this:
<div id="container"> <!-- Wraps all the content on the page -->
<div id="header"> <!-- Wraps and separates the header from the rest of the content -->
<div id="mainMenu"> <!-- Wraps the main navigation menu on the top of the page -->
Menu goes here
</div> <!-- END mainMenu -->
</div> <!-- END header -->
<div id="pageBody"> <!-- Wraps the main bulk of the content below the header -->
<div id="sidebar"> <!-- Wraps the sidebar inside the pageBody box -->
Sidebar content goes here
</div> <!-- END sidebar -->
<div class="mainContent"> <!-- Wraps the actual page text and keeps it separate from the sidebar -->
Page content goes here
</div> <!-- END mainContent -->
</div> <!-- END pageBody -->
<div id="footer"> <!-- Wraps the footer -->
Footer content goes here
</div> <!-- END footer -->
</div> <!-- END container -->
Basically, we have a box called #container that holds all the content. At the top we have a new box called #header that contains the page heading, and within this box there is another box called #mainMenu that holds the main menu. Below the #heading box is a new box called #pageBody, which in turn holds two more boxes called #sidebar and .mainContent that hold the sidebar and main text content, respectively. At the bottom there is a box called #footer that contains all the footer information.
You may have noticed that unlike all the other <div> tags, the one that wraps the main text content has a class rather than an id attribute. In standards-based HTML coding, the id and class attributes are used for two different things: While the id is used for instances that happen just once per page, the class is used for things that can be repeated several times in one page. If you imagine for a second that this layout was for a blog, the .mainContent div should be a class rather than an id because you will have multiple instances, one for each post, on the same page. Note that if you use ids or classes in the wrong way, the page will still display properly but the code will not comply with web standards.
Styling the Content
Before creating the layouts, let’s take a moment to style the page content and make it look a little less bland. This will not only teach you how to use the powerful CSS tools built into Expression Web 2, but will also show you how you can use divs to create different styles for the different sections of the page. We will place the styles in an external style sheet to keep the markup and styling completely separate.
- In Expression Web 2, close the Toolbox task pane. You won’t need it for this tutorial. Click the Manage Styles task pane to activate it and click the New Style button to open the New Style dialog.
- Under Selector write body, or select body from the drop-down menu.
- Under Define in select New style sheet from the drop-down menu.
- In the Font category set Font-family to Arial, Helvetica, sans-serif. This sets the font family for the whole page unless otherwise specified (Figure 2).
Figure 2. Setting the default font family
- In the Background category set the background-color to #FFFFFF (white). (This is not strictly necessary, but in some cases users set the default background color of their browser to something strange like hot pink, and if you haven’t defined a body background color, your page will end up hot pink on these browsers.)
- When you click OK, a pop-up will appear asking you if you want to attach the style sheet for the new style (Figure 3). Click Yes and a new CSS file will be created for you.
Figure 3. Attaching the style sheet
- Select the tab for the new CSS file from the top of your workspace (it should be called “Untitled_1.css”) and save it as left-fluid-wrap.css in the same folder as your index.html file. Expression Web 2 will automatically link the two files together.
When you go back to the index.html file and look at it in Design View, you’ll see that all the text now has the Arial font rather than the default Times New Roman, and the body style is now listed in the Manage Styles task pane on the right (Figure 4).
Figure 4. The page with the body style set
Create a horizontal menu
Next you are going to style the main menu so that it appears horizontally rather than vertically. This is a much simplified version of my article
The No-Code Way to a Pure CSS Horizontal Drop-Down Menu with Expression Web, which appeared in the November 2008 Expression newsletter. The following steps can be done with the index.html page open in Design View:
- Wrap the menu in a box: In the Manage Styles task pane, click New Style to open the New Style dialog. Give the new style the selector name #mainMenu (the “#” prefix means it’s an id. If it is a class, the prefix is a punctuation mark “.” ) and make sure it is defined in the existing style sheet left-fluid-wrap.css. Under Font set the font-size to 0.8em to make it a bit smaller. Under Border set the border-style to solid, the border-width to 1px and the border-color to #808080. Leave the Same for all boxes checked for all of them to draw a box around the whole menu. Click OK to apply the style and you’ll see the menu now has a grey box around it (Figure 5).
Figure 5. Placing a grey box around the menu
- Get rid of unwanted indentations: By default, unordered lists are indented from the left and have a lot of space on the top and bottom. Different browsers use either the padding or margin attributes to achieve this; so, to avoid the menu shifting around depending on the browser, you need to set these values manually. Create a new style and give it the selector name #mainMenu ul. This style will apply only to the unordered list(s) within the #mainMenu div. Go to the Box category and set the following values: padding-top: 3px, padding-right: 0px, padding-bottom: 3px, padding-left: 0px. This gives the content 3 pixels of “breathing space” before the outline above and below, and sets the left and right padding to zero. Set the margin to 0px for all (Figure 6). You won’t see much of a difference when you click OK, but this step is important, so don’t skip it.
Figure 6. Setting margins for the main menu
- Make the menu horizontal: To make the menu horizontal you need to change the display property of the unordered list elements from the default block to inline. Create a new style and give it the selector name #mainMenu li. (You could be more specific and call it #mainMenu ul li, but in this tutorial that kind of micromanagement is not necessary) Under the Layout category, set display to inline. When you click OK the menu items will appear next to one another on a line.
- Space the buttons out and get rid of the underline: Right now the buttons are jammed together and they still have that ugly underline. We can fix both of these issues in one sweep: Create a new style and give it the selector name #mainMenu li a. This style will affect all links (anchors) in list elements inside the #mainMenu div. Under the Font category, check the none box under text-decoration. This gets rid of the underline. Set the color to #333333 as well. Then go to the Box category and set the padding attributes as follows: padding-top: 3px (to match the padding you set earlier), padding-right: 10px, padding-bottom: 3px, padding-left: 10px. This creates a 20px buffer between each of the buttons. Now the menu looks like a menu.
- Make a fancy hover effect: To make the menu a little more fun, we are going to add a cool hover effect. This is done by changing the background and font color when the mouse hovers over the link. Create a new style and give it the selector name #mainMenu li a:hover. “:hover” is a pseudo-class that is only triggered when the mouse hovers over an object; in this case, an anchor. Under Font, change the color to #FFFFFF (white), and under Background, change the background-color to #808080. Click OK and save the page.
- Save Embedded Files: When you save the index.html page, a dialog opens asking if you want to save embedded files. This is because all the styles you have created were actually placed in the attached CSS file.
If you test the page in your browser now by clicking F12, you’ll see that when you hover your mouse over the menu buttons, the background changes to a grey box for a neat visual cue.
Create a styled sidebar
A common element of modern web sites is the sidebar. The sidebar usually contains menus, links to the most popular pages, advertising or any number of other elements. The great thing about the sidebar is that it provides the visitor with important information and at the same time offers you a chance to make a more visually interesting layout. Because the sidebar is contained inside its own div, it can be set up with its own styling to look different from the rest of the page:
- Make the sidebar look like a sidebar by boxing it in: Create a new style with the selector name #sidebar. This is the box that wraps everything in the sidebar and thus where you define the size and appearance of the box itself. Under Font set the font-size to 0.8em like the other menu. This makes the text a bit smaller and generally looks better. Next, give the box an outline by going to Border and setting border-style to solid, border-thickness to 1px and border-color to #808080. By default, the content of a div is aligned with the edges of the box. But since the box now has an outline, the content needs some breathing space. Go to Box and set the padding to 10px. This creates a 10px buffer between the inner edges of the box and the content. We’ll get back to the margin later. To set how wide the sidebar should be, go to Position and set the width to 250px (you can change this value to whatever you want to fit your design). Click OK and you’ll see that the sidebar content is now contained in a box like in Figure 7.
Figure 7. The sidebar after its box attributes are set
- Style the unordered list: Sidebars will usually contain some kind of menu in the form of an unordered list. But as before, the standard unordered list is not very attractive. Fortunately, it is easy to make it look both fancy and functional. First, we need to reset the indentation so it aligns with the rest of the text. Create a new style with the selector name #sidebar ul. Go to Box and set both padding and margin to 0px. Click OK and you’ll see that the list text now aligns with the other text while the bullets are shifted to the left and almost out of the box. To get rid of the bullets and make the list more stylish, create a new style with the selector name #sidebar ul li. Go to List and set the list-style-type to none from the drop-down menu. This gets rid of the bullets. Now for some fancy styling: Sidebar menus tend to look better if each element is slightly indented and separated by a thin horizontal line. To create the horizontal line go to Border, uncheck the Same for all boxes and set the bottomborder-style to dotted, bottom border-thickness to 1px and bottom border-color to #CCCCCC. If you click the Apply button you’ll see that the list items now have a thin dotted line underneath (Figure 8) but they need to be spaced out more to finish the look. Go to Box, uncheck the Same for all box next to padding and set padding top and padding bottom to 5px and padding left to 10px. Click OK and you’ll see that each list item now has a dotted line on the bottom, 5px breathing space above and below and that the text is indented 10px from the left.
Figure 8. Setting the dotted line below each list item in the sidebar
- Style the links: As always, the links are a hideous blue with a nasty underline. To change this, create a new style with the selector name #sidebar ul li a. Under Font, check the none box under text-decoration to get rid of the underline, and set the color to #CC3300. Click OK and the sidebar links are changed to a nice warm red color. To give the visitor a visual cue that she is hovering over the link, create a new style with the selector name #sidebar ul li a:hover and set the color under Font to #800000. Click OK, save the page and the CSS file and test it in your browser to ensure that the links change color when you hover over them (the pseudo-classes cannot be previewed in Design View in Expression Web 2 but have to be tested in a browser).
- Make a fancy hover effect: To take sidebar lists (or any list for that matter) to that next level, I often attach a fancy hover effect to the list items. This is done by attaching a :hover pseudo-class to the li selector: Create a new style and give it the selector #sidebar ul li:hover. This style will be applied whenever the mouse hovers over an unordered list item in the sidebar, regardless of whether there is a link in it or not. Under Background, set the background-color to #CCCCCC. This will change the background of the entire list item to a light grey. Click OK to apply the new style and save the page and the new CSS.
When you preview the page in your browser, you’ll see that when you hover the mouse over each of the list items in the sidebar, the background of that list item turns grey without the link being activated (Figure 9). To activate the link, you have to hover over it directly. Technically, this is purely a visual effect; but it serves a purpose by giving the visitor a visual clue about what list item she is hovering over.
Figure 9. The finished styling of the sidebar
Important note:Pseudo-classes attached to non-link elements like list items are not supported in older browsers, most notably Internet Explorer 6. For visitors using these browsers, the fancy hover effect will not take place; but otherwise there is no difference. In other words, it is safe to use even for older browsers.
End it with a fancy footer
The footer can be used for many things, most often copyright messages, a secondary menu or information about the page author, etc. Some simple styling can be added to make the footer stand out and finish off the page in a nice way:
- Create a new style with the selector name #footer. Under Background set the background-color to #333333. This creates a nice dark grey background. The default font HTML font color is black, so now that the background is dark, the font color has to be changed. Under Font, change the font-size to 0.8em and the color to #CCCCCC, which is a light grey. I find that shades of grey are less harsh to look at than hard white and hard black. To make the footer a little more substantial, go to Box and set padding top and padding bottom to 10px. Finally, to center the text in the footer, go to Block and set text-align to center.
- Footers usually contain links, so these also need to be styled. Create a new style with the selector name #footer a. Under Font, set the color to #CC3300 and check the none box under text-decoration. Create a final style and give it the selector name #footer a:hover. Set the Font color to #FF9900.
Creating a fluid left-aligned wrap layout using Float and Clear
Now that the content of the page has been styled, all that is left is to organize the layout of the page. You can use several techniques to create CSS layouts. In this tutorial you’ll learn the easiest and safest method, which uses the float attribute to place content. You can also use what is known as positioning ,but this requires a firm understanding of the different positioning attributes and how they interact. My experience is that positioning often gets confusing and messy, and in the end float does the same job just as well.
The fluid left-aligned layout is one in which the width of the page is “fluid,” meaning it changes in accordance with the width of the window rather than being fixed. This layout is rare these days, usually because designers like to make graphic-heavy layouts that require fixed widths, but it is important to know and a good starting point for the other layouts. What we want is a page where the header, menu and main content are all aligned to the left and stretching all the way to the right of the screen. The sidebar should rest on the right hand side of the screen with the main content text wrapping around it to fill in the empty space.
As you saw in the beginning of this article, the page has a box called #container that in turn is divided into three sections: #header, #pageBody and #footer. #pageBody is further divided into two areas; .mainContent and #sidebar. To position these sections in relation to each other, all you need to do is create specific styles for each section:
- To create some breathing space on the left and right sides of the screen, create a new style with the selector name #container. Under Box, set the left and right margin to 20px. When you click OK, the new style is added to the bottom of the list in the Manage Styles task pane. To keep the CSS organized properly, it should really be placed where it appears in the order, which is directly under the #body style. To fix this, simply click-and-hold the #container style and drag-and-drop it to the position directly under #body. This is a simple and clean way of quickly reorganizing the code in external CSS documents without ever actually touching the code. Your Manage Styles pane should now look like Figure 10.
Figure 10. Organizing the style sheet
- Make a small gap between the #header box and the #pageBody. Create a new style with the selector name #pageBody, go to Box and set margin top to 5px. After clicking OK, use the same technique as before to place the new style above the #sidebar style.
- Now for some CSS magic: To place the sidebar on the right side of the screen, you only have to make one change to the #sidebar style! In the Manage Styles task pane, right-click the #sidebar style and select Modify Style from the pop-up menu. This opens the Modify Styles task pane. Go to Layout and set float to right. Click Apply and you’ll see that, like the name suggests, the #sidebar box will now “float” to the right of the containing box #pageBody. And because nothing else has been specified for the remaining text, it wraps around the sidebar box to fill out the space below it. To avoid the remaining text from jamming right up against the side of the sidebar box, go to Box and set the left margin to 10px. Click OK, save the page and the CSS and preview the page in your browser.
- To make the layout as clean as possible, the main text should be justified. To do this, create a final style with the selector.mainContent, go to Block and set text-align to justify. Click OK and you have your first layout!
Open the final layout in your browser and you will see that as you resize the browser window, the text on the page as well as the main menu and the footer will “flow” and reorganize itself to fill out the whole browser space.
Variation on the theme
You may have figured this out already: If you want the sidebar to be placed on the left rather than the right side, you only have to make two changes to the #sidebar style: switch the float from right to left and switch the 10px margin from left to right.
Upgrading to a Fixed Width Left Aligned Layout
Now you have two options: Either keep working on the same style sheet, or make a new one so you can keep the current layout to play with later. Here is how to make a new style sheet to work on without having to redo everything you’ve done so far:
- In the Folder List task pane, right click the left-fluid-wrap.css file and select Copy from the pop-up menu.
- Immediately afterwards, hit Ctrl+V on your keyboard, and a copy of the file called left-fluid-wrap_copy(1).css is pasted into the task pane.
- Right-click the new file and select Rename from the drop-down menu. Give the file the new name left-fixed.css.
- In the View Pane change the setting to Split View and scroll to the very top of the code view. Here you will find a line that looks like this: <link href="left-fluid-wrap.css" rel="stylesheet" type="text/css" />. Edit the code directly in code view by replacing href="left-fluid-wrap.css" with href="left-fixed.css". This changes the attached CSS document to the copy you just created. When you click anywhere inside Design View you will see this change reflected at the top of the Manage Styles task pane, as shown in Figure 11.
Figure 11. Switching to the left-fixed.css style sheet
For this layout you will make two major changes: First, the width of the page content will be restricted to a specific size. Second, the text wrap will be changed so that the text remains the same width throughout the page, leaving the area below the sidebar empty. For the following I am assuming you did not change the position of the sidebar from right to left. If you did, change it back by reversing the variation procedure.
- Set the width of the container: Since all the content on the page is placed inside the #container box, the easiest way of constraining the width of the content is by setting the width of the container. Right-click the #container style in the Manage Styles task pane and select Modify Style from the drop-down menu. Under Position set width to 800px.
- Make room for the sidebar:The easiest way to remove the wrap that puts the text below the sidebar is to simply reduce the area the text can appear on. This can be done with fixed width and positioning, but that’s a somewhat complicated procedure. A much easier and just as effective method is to simply give the #mainContent a thick margin that accommodates for the sidebar: Right-click the #mainContent style and select Modify Style. Under Box set the right margin to 282px. 282px accommodates for the width of the sidebar (250px) plus the 10px padding on either side plus the 1px border on either side plus the 10px margin on the left side.
That really is all there is to it. Now you have a fixed-width layout that hugs the left side of the screen. As before, to place the sidebar on the left side instead, make the same changes I listed above and add to the list that you need to change the 282px padding in #mainContent from right to left.
The Elusive Centered Page Layout
Invariably everyone who starts to work with web design run into the same problem: How do I make a centered web layout? I’ve shown you how you can use the float attribute to place a box on the left or right of the screen, and this technique can be applied to any element in the layout. For instance, if you want to move the entire layout you just created over to the right side of the screen, all you have to do is set the float value of the #container style to right. But as you have probably noticed, there is no option to float things to the center. So now what?
Traditionally in the days of table-based designs, the solution to this problem was simple: Set the text alignment of the table to center. But if you try setting the text alignment of the outermost box of a CSS layout (in this case the body element), all you achieve is that all non-aligned text in the page is aligned to the center of its containing box. The page itself remains stubbornly at the left side of the screen.
The solution to this seemingly impossible problem is so elegant and obvious that you’ll probably want to slap yourself for not having thought of it yourself. (If the urge to slap yourself gets too strong, try drinking a tall glass of ice water and listen to some calming music. It helped me when I figured this thing out.)
To center the layout on the page, right-click the #container style and select Modify Style from the drop-down menu, go to Box and set the left and right margin to auto (Figure 12). Click OK, save the page and CSS and preview the page in your browser.
Figure 12. Setting margins to auto
Like magic, the page now aligns perfectly to the center and continues to do so even if you resize the window. So why is this happening? When the page is populated with content, the browser sees that the left and right margins are supposed to be equal, so it takes the total width of the window, subtracts the defined width of the box to which the margins are attached, and divides that number in half, setting the two margins to the same value. See, I told you it was simple!
One HTML File, Endless Layout Variations
There you have it: Without making any changes to the HTML file, you have now applied the three most common layouts in several different variations—and the techniques and methods you’ve learned can be applied to any CSS layout element to make incredibly complicated layouts. I used these exact methods to style both my design blog
Design is Philosophy and the
Reader’s Companion, a site for
my book about Expression Web 2. There really are no limits to what you can do when you grasp how powerful CSS is as a layout tool. And the cool part is that since none of the styling is contained in the markup, you can make sweeping layout and styling changes throughout a site simply by changing the CSS file. That kind of flexibility could never be offered by tables or frames. And the CSS layout techniques can be applied to any site, whether it consists of static HTML pages, DWTs, or is powered by ASP.NET or PHP. When you understand CSS as a layout tool, there really are no limits to what you can do (on the web that is).
A Neat Trick for Good Measure
If you scroll down to the bottom of the centered page layout, you’ll see that the footer is the same width as the rest of the page content. But sometimes you want the footer to span the whole width of the page. To do this, you have to make a slight modification of the HTML code. Or maybe “tiny” would be a better word:
Go to the very bottom of the index.html page in Code View and find the following group of lines:
</div> <!-- END pageBody -->
<div id="footer"> <!-- Wraps the footer -->
<p>The footer usually contains regular paragraph items along with a couple of <a href="#" title="Footer link">links</a> that <a href="#" title="Footer link 2">point</a> to other pages or sites.</p>
</div> <!-- END footer -->
</div> <!-- END container -->
As you can see, the #footer is placed within the #container, which is why its width is constrained. To move the #footer out of the #container, highlight the line reading </div> <!-- END container -->, hit Ctrl+X on your keyboard to cut it out, place the cursor at the end of the line that reads </div> <!-- END pageBody -->, hit Enter to create a new line and hit Ctrl+V to paste the line of code back in. The resulting code should match the code in Figure 13. If you save the page and preview it in your browser you’ll see that now the footer stretches across the entire window. If you want to get rid of the white margins on the page, set the padding and margin attributes of the body style to 0px.
Figure 13. Placing the footer code outside the container for rest of the page content
That really is all there is to it. Now go forth and design! And feel free to drop me a line through
my blog if you have any questions.