CSS Page Layout   The next step to better design


We strongly recommend that you read Chapter 11 of the Head First HTML and CSS book as a gentle explanation for this topic. The material in these notes comes from Chapters 11, 12, 13 of the book CSS The Missing Manual.

Introduction

As you have noticed so far, HTML displays content from top to bottom, with most elements stacked as blocks. Today, we will see how to use CSS to put elements everywhere in the page, in order to create more visually appealing pages.

Most web page designs on the web fall in one of the two types of layout: fixed-width or liquid.

Fixed-width design gives you more control over how your pages will look, but will cause inconvenience for users with small monitor devices (a lot of scrolling). Liquid designs, which grow or shink to fit a browser window, are better for users, but make things more difficult for you the designer. A compromise between these two types is the elastic design, which has been declining in use.

  • A perfect example of a fixed-width layout is the NY Times website. Resize your page. Once your screen has become less than 970px, you'll see that the scrollbars will show up and the page doesn't change. Most websites on the web have a fixed width, usually under 1000px (with a common value of 960px).
  • A perfect example of a liquid layout is the new Google Maps website. Again, resize your browser to see how the page content shrinks or grows with your window size. This type of design makes the best use of available space, but you'll need to make sure that it looks well on all different device sizes. Our own website is also an example of fluid design. Resize the window to experience it.

How CSS layout works

Web page layout involves putting content into different regions of the page. In order to do this, the content needs to be in container tags such as: nav, header, section, footer, picture, aside, and the ubiquitous div. Keep in mind though that you don't need to use div if it's not called for. Elements that are displayed as blocks, such as ul, ol, and p can be also moved everywhere in the page.

Two Techniques for CSS Layout

There are two general techniques used for layout: floats and absolute positioning. Floats are by far the most used. HTML elements have a property float, which will make the element float on the left or the right side of the page. Meanwhile, absolute positioning allows you to place an element anywhere on the page with pixel-like accuracy. This technique doesn't go well with the liquid design, but is good for positioning things like logos, etc. that need always be in a certain place.

Layout Strategies

Web page layout with CSS is more of an art than science, there is no formula for marking up your HTML page or creating the CSS. CSS layout is something that you will learn through experience, learning the different CSS propertis, following tutorials, and practicing a lot. What follows in this section is a set of guidelines that can be useful as you start learning about this topic.

  1. Start with your content. Design starts with your content (headlines, text, links, photographs, etc.), not with colors, fonts, or icons. It is the page message that should dictate the design. For example, if the goal of a student organization page is to get more student to join them, you can put a large photo of the members doing something fun or interesting, together with quotes from them. Then you use style to make them compelling.
  2. Mock up your design. Don't start your design with code, start with a drawing. Using a drawing program (Paint, Photoshop, Illustrator, etc.) gives you freedom to explore different colors, fonts, images, and positioning, without having to write code. This way you can experiment faster with many choices. If your page needs user interface elements such as buttons, tabs, etc. you can use the free stencil kit from Yahoo, together with Photoshop.
  3. Identify the boxes. Once you are satisfied with your mockup, you can start thinking about the HTML structure. Basically you need to identify which elements look like individual boxes, because they will have to be in container tags in your HTML.
  4. Remember background images. Very often, you can more easily place an image with the background-image property than the <img> tag. This is because you can put other information on top of this image, without needing floating. However, you should know that background images are not printed, thus, don't put important information (such as maps) as background.
  5. Layering elements. Tools like Photoshop use the notion of layers to float several things on top of each other. To do the same on a web page, there are two options: use the background-image property to put text on top of images, or use the position property to lay images or icons on top of text.
  6. Don't forget margins and paddings. Often, you might not need to use sophisticated CSS for layout. A good use of the margin and padding properties can take you really far (especially when combined with the background image property).

Float-based Layouts

In this section, we will show with different examples how to build float-based layouts. Such layouts make use of the float property to position elements side by side and create columns. You can also use float to create a wrapping effect. This is because the floated element is removed from the flow of the document and what comes after it moves up and wraps around the float. [Note: Your book has a very detailed description of what the flow of a document is.]

Floating an image

As you know, an image is an inline element. To remind you of that, look at this example and resize the browser page to see what happens to the images. You also can use Chrome's Inspect Element to notice that <img> is nested within the p. Now, let us look at the same page after applying a simple style with centered fixed-width layout (width and margin for body), and the rule img {float: right;}. Notice how now the image is strictly on the right side of the document, and the text of the paragraph wrapping around it.

Floating a div (or semantic container)

Let us now see what happens when we float a container element, such as a div, figure, footer, etc. Here is the unstyled page, where we put the img inside the figure container. Notice how this time the images are not inline anymore.

If we apply now the floating property to the figure, element, we get the same effect as before, with the distinction that figure already has some default values for the margin assigned by the browser.

The float property takes only three values: left, right, and none. The last value is used when you want to prevent an element from floating.

Now that we learned about the property float, let's see how it can be used to create a layout with columns.

Two-column layout

In order to have a two-column layout, we need to have two containers which can meaningfully stand next to each other; for example, a section and a aside. Let's add first a aside element to our Hunger Games example. Then, we apply some minimal style to this element, in order to float on the left side, as shown below, getting now a new version of our page.
aside {
    float: left;
    border: 1px black solid;
    padding: 5px;
}
Important Note: The width and height of every container element depends on the amount of content (text or images) inside the container.

As you see, the aside box size can be calculated based on the values for margin, border, padding, and content size (e.g. the width: 185px = 0 + 1px + 5px + 173px + 5px + 1px + 0).

screenshot of sidebar box screenshot of sidebar box
The size of a container box depends on its content and styling.

If you want the size of the column to be something you desire (e.g., instead of width of 185px, to be 200px), you can do the reverse calculation to find what the width of the content should be, using a simple equation. For example, 200px = 0 + 2*1px + 2*5px + Xpx. Solving this, we get width=188px. This means that in our rule we should set the width: 188px;, in order to get the real size of the column to 200px on the browser page.

One could do the same for the height, but this is not very useful, because if the adjacent column gets more content, we'll need to recalculate. Thus, instead of setting the height of the floating column, we set a margin for the column which is not floating, in our example, section. Depending on whether the floating column would be on the left or the right side, we need to set margin-left or margin-right to a value slightly larger than the width of the floating column. This is how our example will look like with the new added rule: section {margin-left: 210px;}.

Summary: The two-column layout

  1. Wrap each column in a container, for example, aside and section (or a div with an idattribute).
  2. Float one container (in our case, aside) either left or right.
  3. Set a desired width for the floated element.
  4. Add a margin (left or right, matching the floating side) to the fixed element.

Three-column layout

Going from a two-column layout to a three-column layout is easy. Can you think of the changes you will need to make to your HTML and CSS code? To challenge yourself, stop reading at this point and go and experiment with the code from the two-column layout (get the files from the links above). Then, check our solution. Here is a summary of the steps we performed:
  • Added a new aside element (before the section).
  • Added an id attribute to each aside element.
  • Used these two new id-s as selectors in the CSS code (the rules are identical, with the exception of float.
  • Added margin-right: 210px; to the section rule, in order to allow space for the new floating element.
Important Note: When using this technique (known as positive margins), the floating elements need to be placed before the main content in the HTML file, otherwise, you will not get the desired effect.

Float Problems

Working with floating elements can often cause unexpected problems. In the following, we will describe two of them together with the solutions.

Clearing Floats

We saw that one of the things that happens with floats is that other content wraps around them. Sometimes that might be good, but sometimes it isn't. A problem that occurs often is with the footer element of a page, when the main content is shorter than one of the floating columns. To illustrate this problem, we modified the Hunger Games example to show what happens with the footer (see also image below).

Fortunately, there is an easy fix for this problem. We add the property clear in the rule of the element we want to stay away from the floats, in our case, footer.

Afetr making this change, the footer stays at the bottom of the page.

screenshot of problem with floating
The footer has moved up below the non-floating element.

Containing Floats

Another problem occurs when a floating element contained within another element is larger than the latter. This becomes obvious when the container has a background color or border. In our ongoing Hunger Games example, we changed the background color of the section element to olive, and as you can see in the photo below, the float element pops out of the container. There are several solutions to this problem, but we will show the two simplest.
  1. Add an element at the bottom of the container, in order to use clear. In our solution to this problem, we added a <br class="clear"> element before the end of the section and a CSS rule for it br.clear {clear: both;}.
  2. Use a dedicated CSS property for the container element, overflow: hidden;. Here is again the example with the solution.
screenshot of problem with floating
The problem created by a floating element bigger than its container.

Positioning Elements on Page

At the beginning of these notes we mentioned that floats are the most used technique for designing layouts. However, there is another technique, positioning, which has its good uses in particular situations.

We achieve positioning of elements throught the property position, which can take these values:

  • absolute
  • relative
  • fixed
  • static (this is the default state of every element)

The values absolute and fixed are very similar in their syntax (though they create different effects) and more easy to understand. The value relative is a bit more tricky, because its meaning is not in par with how we use the word in everyday language. To explain these values, we will show in the following an example for each. You should look at the HTML and CSS files of each example to better understand what is going on.

position: absolute

We can use this style to set an element in a desired location in the page, by additionally specifying the values for at least two other properties from left, right, top, and bottom. These properties specify the distance (in pixel or some other units) from the (0,0) coordinates of the viewport (top-left corner of the browser viewing area). To see this in action we have a modified version of our Hunger Games example, and we will try to position the figure to some other location, as shown in this styled version of the example. This effect was achieved with this CSS code:
figure {
  position: absolute;
  top: 350px;
  left: 500px;
  border: 1px black solid;
  padding: 3px;
}
Notice how the figure lays on top of the text. This is because by becoming absolute, the other elements are not aware of it anymore, so they cannot flow around it. Additionally, try to resize your browser window. The placement of the figure doesn't change.

position: relative

Suppose we want to put a caption on the figure, sitting on top of it, instead of below it. In this case, we will need to use the relative position. However to achieve this, we need to do two things:
  1. Declare which is the element relative to which this positioning is going to happen.
  2. Declare as absolute the element we want to position, and specify its coordinates relative to its parent.
This new example, creates a caption over the figure with the following code:
figure {
  position: relative;
  border: 1px black solid;
  padding: 3px;
  width: 400px;
}
figure span{
  position: absolute;
  bottom: 15px;
  left: 4px;
  right: 4px;
  color: yellow;
  background-color: black;
  opacity: 0.5;
  text-align: center;
  font-weight: 200%;
  padding: 5px;
}

position: fixed

This positioning is very similar to the absolute one, with the difference that the element remains in its position all the time, while the rest of the page scrolls up and down. It is useful for fixing navbars or sidebars in one position. See how the aside element remains fixed in our example, with the code below:
aside {
  position: fixed;
  top: 80px;
  border: 1px black solid;
  padding: 5px;
  width: 188px; /* this value will make sure the sidebar box will occupy 200px */
}