13
Understanding and Unleashing the Power of CSS Layouts http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10] Welcome Sign in Home Community Library Downloads Forums Expression > Newsletters > January 2009 Newsletter Understanding and Unleashing the Power of CSS L... Understanding and Unleashing the Power of CSS Layouts Author: Morten Rand-Hendriksen, Creative Director, Pink & Yellow Media Blog: http://blog.pinkandyellow.com/ Expression Newsletter, 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: 1. 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. 2. 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). Expression Newsletter Inspiration and information--you'll find it in the Expression Newsletter. Tips from design experts Step-by-step tutorials Skill-building videos Read the latest issue Subscribe now Discussion Forums Expression Studio Forum Expression Blend Forum Expression Web Forum Expression Design Forum Expression Media Forum Expression Encoder Forum Support Expression Web Solution Center Expression Design Solution Center Expression Media Solution Center Expression Studio Suggestions United States - English Microsoft.com Expression Product Site Suggestions Search with Live Search Expression Microsoft.com Entire Web Close

Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Welcome Sign in

Home Community Products Gallery Learn Library Downloads Forums

Expression > Newsletters > January 2009 Newsletter > Understanding and Unleashing the Power of CSS L...

Understanding and Unleashing the Power of CSS LayoutsAuthor: Morten Rand-Hendriksen, Creative Director, Pink & Yellow MediaBlog: http://blog.pinkandyellow.com/

Expression Newsletter, 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 onlyare they easy to maintain and update, but they also make the web a better place for people who, for one reason oranother, 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 donemore out of a lack of any better tool than anything else; but the custom stuck, and soon the web was littered withgreat-looking sites that had nightmarish HTML markup you would need a CIA decoder to figure out. As aconsequence, although the sites looked great for the average user on a normal browser, users on slower or outdatedbrowsers, on text-only browsers or those with disabilities who use text-to-speech or other non-visual browsers werepresented with messy and unreadable pages.

As the need for better accessibility and more advanced web sites grew, designers and developers started migratingaway from table-based layouts and toward Cascading Style Sheets (CSS). This layout tool had many advantages overtables, most notably that the styling and layout code was kept separate from the markup, often in entirely separatefiles. As a result, one CSS document could contain the styling for multiple HTML pages, and with that the designernow 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 toolof choice for designers and developers, and its versatility has even taken it out of the classic web design world andinto regular programming. It may surprise you to learn that many software applications like the popular Firefoxbrowser 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 andpoorly understood, and even seasoned designers and developers often find themselves scratching their heads when itcomes to building pure CSS based layouts and sites that work properly. One of the main questions that keeps comingup 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 styleswithout 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 meansyou never really understand what is going on and how the code works. It’s much better to build something fromscratch.

In this tutorial you will learn how to build the three most common CSS layouts using the CSS tools found inExpression Web 2. These are the fluid width layout, the left-aligned fixed-width layout and the centeredlayout. You can see the final results on my sample page. You will learn how to apply all of these layouts to the sameHTML document without making any changes to the markup, and how to make variations of the different layouts in afew simple steps. In the end you will have a firm understanding of the basics of CSS layouts and also have thefoundation 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 stylingcode from the actual content of the page, leaving the HTML markup nice and uncluttered and easy for text-onlybrowsers to read. To save some time, I’ve created a standard HTML page with all the markup you’ll need for thistutorial.

The first step of this tutorial is to create a new site and import the HTML markup into Expression Web 2:

1. Open Expression Web 2, click File > New > Web Site and select Empty Web Site from the menu. Save thenew project under a new folder called CSS Layouts where you normally save your Expression Web 2 projects.

2. 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 pagedirectly inside Expression Web 2 (see Figure 1).

Expression Newsletter

Inspiration and information--you'llfind it in the Expression Newsletter.

Tips from design experts

Step-by-step tutorials

Skill-building videos

Read the latest issue

Subscribe now

Discussion Forums

Expression Studio Forum

Expression Blend Forum

Expression Web Forum

Expression Design Forum

Expression Media Forum

Expression Encoder Forum

Support

Expression Web Solution Center

Expression Design SolutionCenter

Expression Media Solution Center

Expression Studio Suggestions

United States - English Microsoft.com

Expression Product Site

Suggestions

Search with Live Search

ExpressionMicrosoft.comEntire Web

Close

Page 2: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Figure 1. Opening the unstyled document in Expression Web 2

3. 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 ...)</div>

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 doesnot 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:

<div>Some text</div>

the browser draws an invisible box around it. If you use CSS to give that tag a background colour or a border, it willbe 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 pageelements and will be used to create the layout. Basically, we are going to define the size and shape of each box andtell 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 --><h1>Main heading</h1><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 thesidebar --> 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 #headerthat contains the page heading, and within this box there is another box called #mainMenu that holds the mainmenu. Below the #heading box is a new box called #pageBody, which in turn holds two more boxes called #sidebarand .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 classrather than an id attribute. In standards-based HTML coding, the id and class attributes are used for two differentthings: While the id is used for instances that happen just once per page, the class is used for things that can berepeated several times in one page. If you imagine for a second that this layout was for a blog, the .mainContent div

Page 3: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

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 complywith 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. Thiswill not only teach you how to use the powerful CSS tools built into Expression Web 2, but will also show you howyou can use divs to create different styles for the different sections of the page. We will place the styles in anexternal style sheet to keep the markup and styling completely separate.

1. In Expression Web 2, close the Toolbox task pane. You won’t need it for this tutorial. Click the Manage Stylestask pane to activate it and click the New Style button to open the New Style dialog.

2. Under Selector write body, or select body from the drop-down menu.

3. Under Define in select New style sheet from the drop-down menu.

4. In the Font category set Font-family to Arial, Helvetica, sans-serif. This sets the font family for the whole pageunless otherwise specified (Figure 2).

Figure 2. Setting the default font family

5. In the Background category set the background-color to #FFFFFF (white). (This is not strictly necessary, butin some cases users set the default background color of their browser to something strange like hot pink, and ifyou haven’t defined a body background color, your page will end up hot pink on these browsers.)

6. 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.

Page 4: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Figure 3. Attaching the style sheet

7. Select the tab for the new CSS file from the top of your workspace (it should be called “Untitled_1.css”) andsave it as left-fluid-wrap.css in the same folder as your index.html file. Expression Web 2 will automatically linkthe 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 Arialfont rather than the default Times New Roman, and the body style is now listed in the Manage Styles task pane onthe 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

Page 5: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

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.htmlpage open in Design View:

1. 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 apunctuation mark “.” ) and make sure it is defined in the existing style sheet left-fluid-wrap.css. Under Font setthe 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 todraw a box around the whole menu. Click OK to apply the style and you’ll see the menu now has a grey boxaround it (Figure 5).

Figure 5. Placing a grey box around the menu

2. Get rid of unwanted indentations: By default, unordered lists are indented from the left and have a lot ofspace 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. Createa 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.

Page 6: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Figure 6. Setting margins for the main menu

3. Make the menu horizontal: To make the menu horizontal you need to change the display property of theunordered 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 ofmicromanagement is not necessary) Under the Layout category, set display to inline. When you click OK themenu items will appear next to one another on a line.

4. Space the buttons out and get rid of the underline: Right now the buttons are jammed together and theystill have that ugly underline. We can fix both of these issues in one sweep: Create a new style and give it theselector name #mainMenu li a. This style will affect all links (anchors) in list elements inside the #mainMenudiv. Under the Font category, check the none box under text-decoration. This gets rid of the underline. Setthe 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.

5. Make a fancy hover effect: To make the menu a little more fun, we are going to add a cool hover effect. Thisis done by changing the background and font color when the mouse hovers over the link. Create a new style andgive it the selector name #mainMenu li a:hover. “:hover” is a pseudo-class that is only triggered when themouse hovers over an object; in this case, an anchor. Under Font, change the color to #FFFFFF (white), andunder Background, change the background-color to #808080. Click OK and save the page.

6. Save Embedded Files: When you save the index.html page, a dialog opens asking if you want to saveembedded 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 menubuttons, 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 popularpages, advertising or any number of other elements. The great thing about the sidebar is that it provides the visitorwith 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 therest of the page:

1. 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 thebox itself. Under Font set the font-size to 0.8em like the other menu. This makes the text a bit smaller andgenerally 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 theedges of the box. But since the box now has an outline, the content needs some breathing space. Go to Boxand 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 to250px (you can change this value to whatever you want to fit your design). Click OK and you’ll see that thesidebar content is now contained in a box like in Figure 7.

Page 7: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Figure 7. The sidebar after its box attributes are set

2. Style the unordered list: Sidebars will usually contain some kind of menu in the form of an unordered list. Butas before, the standard unordered list is not very attractive. Fortunately, it is easy to make it look both fancyand functional. First, we need to reset the indentation so it aligns with the rest of the text. Create a new stylewith the selector name #sidebar ul. Go to Box and set both padding and margin to 0px. Click OK and you’llsee that the list text now aligns with the other text while the bullets are shifted to the left and almost out of thebox. 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 thebullets. Now for some fancy styling: Sidebar menus tend to look better if each element is slightly indented andseparated by a thin horizontal line. To create the horizontal line go to Border, uncheck the Same for all boxesand 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 boxnext to padding and set padding top and padding bottom to 5px and padding left to 10px. Click OK andyou’ll see that each list item now has a dotted line on the bottom, 5px breathing space above and below andthat the text is indented 10px from the left.

Page 8: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Figure 8. Setting the dotted line below each list item in the sidebar

3. Style the links: As always, the links are a hideous blue with a nasty underline. To change this, create a newstyle with the selector name #sidebar ul li a. Under Font, check the none box under text-decoration to getrid of the underline, and set the color to #CC3300. Click OK and the sidebar links are changed to a nice warmred color. To give the visitor a visual cue that she is hovering over the link, create a new style with the selectorname #sidebar ul li a:hover and set the color under Font to #800000. Click OK, save the page and the CSS fileand test it in your browser to ensure that the links change color when you hover over them (the pseudo-classescannot be previewed in Design View in Expression Web 2 but have to be tested in a browser).

4. Make a fancy hover effect: To take sidebar lists (or any list for that matter) to that next level, I often attacha fancy hover effect to the list items. This is done by attaching a :hover pseudo-class to the li selector: Create anew style and give it the selector #sidebar ul li:hover. This style will be applied whenever the mouse hoversover 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 inthe sidebar, the background of that list item turns grey without the link being activated (Figure 9). To activate thelink, you have to hover over it directly. Technically, this is purely a visual effect; but it serves a purpose by giving thevisitor a visual clue about what list item she is hovering over.

Page 9: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

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; butotherwise 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 thepage author, etc. Some simple styling can be added to make the footer stand out and finish off the page in a niceway:

1. 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 thebackground is dark, the font color has to be changed. Under Font, change the font-size to 0.8em and thecolor to #CCCCCC, which is a light grey. I find that shades of grey are less harsh to look at than hard whiteand hard black. To make the footer a little more substantial, go to Box and set padding top and paddingbottom to 10px. Finally, to center the text in the footer, go to Block and set text-align to center.

2. 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 afinal 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 useseveral techniques to create CSS layouts. In this tutorial you’ll learn the easiest and safest method, which uses thefloat attribute to place content. You can also use what is known as positioning ,but this requires a firmunderstanding of the different positioning attributes and how they interact. My experience is that positioning oftengets 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 thewidth of the window rather than being fixed. This layout is rare these days, usually because designers like to makegraphic-heavy layouts that require fixed widths, but it is important to know and a good starting point for the otherlayouts. What we want is a page where the header, menu and main content are all aligned to the left and stretchingall the way to the right of the screen. The sidebar should rest on the right hand side of the screen with the maincontent 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 threesections: #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 eachsection:

1. To create some breathing space on the left and right sides of the screen, create a new style with the selectorname #container. Under Box, set the left and right margin to 20px. When you click OK, the new style isadded to the bottom of the list in the Manage Styles task pane. To keep the CSS organized properly, it shouldreally 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 andclean 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.

Page 10: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

Figure 10. Organizing the style sheet

2. 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 toplace the new style above the #sidebar style.

3. Now for some CSS magic: To place the sidebar on the right side of the screen, you only have to make onechange to the #sidebar style! In the Manage Styles task pane, right-click the #sidebar style and selectModify Style from the pop-up menu. This opens the Modify Styles task pane. Go to Layout and set float toright. Click Apply and you’ll see that, like the name suggests, the #sidebar box will now “float” to the right ofthe containing box #pageBody. And because nothing else has been specified for the remaining text, it wrapsaround the sidebar box to fill out the space below it. To avoid the remaining text from jamming right up againstthe side of the sidebar box, go to Box and set the left margin to 10px. Click OK, save the page and the CSSand preview the page in your browser.

4. To make the layout as clean as possible, the main text should be justified. To do this, create a final style withthe 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 pageas 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, youonly have to make two changes to the #sidebar style: switch the float from right to left and switch the 10px marginfrom 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 thecurrent layout to play with later. Here is how to make a new style sheet to work on without having to redoeverything you’ve done so far:

1. In the Folder List task pane, right click the left-fluid-wrap.css file and select Copy from the pop-up menu.

2. Immediately afterwards, hit Ctrl+V on your keyboard, and a copy of the file called left-fluid-wrap_copy(1).css ispasted into the task pane.

3. Right-click the new file and select Rename from the drop-down menu. Give the file the new name left-fixed.css.

4. In the View Pane change the setting to Split View and scroll to the very top of the code view. Here you willfind a line that looks like this: <link href="left-fluid-wrap.css" rel="stylesheet" type="text/css" />. Edit the codedirectly in code view by replacing href="left-fluid-wrap.css" with href="left-fixed.css". This changes the attachedCSS document to the copy you just created. When you click anywhere inside Design View you will see thischange reflected at the top of the Manage Styles task pane, as shown in Figure 11.

Page 11: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

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 specificsize. Second, the text wrap will be changed so that the text remains the same width throughout the page, leaving thearea below the sidebar empty. For the following I am assuming you did not change the position of the sidebar fromright to left. If you did, change it back by reversing the variation procedure.

1. Set the width of the container: Since all the content on the page is placed inside the #container box, theeasiest 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. UnderPosition set width to 800px.

2. Make room for the sidebar:The easiest way to remove the wrap that puts the text below the sidebar is tosimply reduce the area the text can appear on. This can be done with fixed width and positioning, but that’s asomewhat 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 andselect Modify Style. Under Box set the right margin to 282px. 282px accommodates for the width of thesidebar (250px) plus the 10px padding on either side plus the 1px border on either side plus the 10px margin onthe 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, toplace the sidebar on the left side instead, make the same changes I listed above and add to the list that you need tochange 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 weblayout? I’ve shown you how you can use the float attribute to place a box on the left or right of the screen, and thistechnique can be applied to any element in the layout. For instance, if you want to move the entire layout you justcreated 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 ofthe table to center. But if you try setting the text alignment of the outermost box of a CSS layout (in this case thebody 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 yourselffor not having thought of it yourself. (If the urge to slap yourself gets too strong, try drinking a tall glass of ice waterand 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-downmenu, go to Box and set the left and right margin to auto (Figure 12). Click OK, save the page and CSS andpreview the page in your browser.

Page 12: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

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 whyis this happening? When the page is populated with content, the browser sees that the left and right margins aresupposed to be equal, so it takes the total width of the window, subtracts the defined width of the box to which themargins are attached, and divides that number in half, setting the two margins to the same value. See, I told you itwas 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 commonlayouts in several different variations—and the techniques and methods you’ve learned can be applied to any CSSlayout element to make incredibly complicated layouts. I used these exact methods to style both my design blogDesign is Philosophy and the Reader’s Companion, a site for my book about Expression Web 2. There really are nolimits to what you can do when you grasp how powerful CSS is as a layout tool. And the cool part is that since noneof the styling is contained in the markup, you can make sweeping layout and styling changes throughout a site simplyby changing the CSS file. That kind of flexibility could never be offered by tables or frames. And the CSS layouttechniques can be applied to any site, whether it consists of static HTML pages, DWTs, or is powered by ASP.NET orPHP. 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 restof the page content. But sometimes you want the footer to span the whole width of the page. To do this, you have tomake 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 pagesor 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 keyboardto cut it out, place the cursor at the end of the line that reads </div> <!-- END pageBody -->, hit Enter to create anew line and hit Ctrl+V to paste the line of code back in. The resulting code should match the code in Figure 13. Ifyou save the page and preview it in your browser you’ll see that now the footer stretches across the entire window. Ifyou want to get rid of the white margins on the page, set the padding and margin attributes of the body style to0px.

Page 13: Understanding and Unleashing the Power of CSS …...If we go back in time, the most common way of creating more advanced web page layout was tables. This was done This was done more

Understanding and Unleashing the Power of CSS Layouts

http://expression.microsoft.com/en-us/dd434643.aspx[10.03.2009 09:45:10]

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 haveany questions.

Manage Your Profile | Legal | Contact Us | Site Feedback | Expression Newsletter

© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement