• 20 hours
  • Easy

Free online content available in this course.

course.header.alt.is_certifying

You can get support and mentoring from a private teacher via videoconference on this course.

Got it!

Last updated on 11/12/18

Positioning in CSS

Log in or subscribe for free to enjoy all this course has to offer!

Here comes the long awaited moment: we're going to learn how to change the position of the items on our page. We're going to need the theory we're going to see here in the next chapter, in which we're going to design our first website together, step by step!

You'll see, there are several techniques for doing the page layout of your website. Each has its advantages and drawbacks and it will be up to you to choose the one that seems best to you according to your case.

Floating positioning

Do you remember thefloatproperty? We used it to float an image around the text (figure below).

The image floats around the text through the float property
The image floats around the text through the float property

It turns out that this property is now used by most websites for... the page layout! In fact, if you want to place your menu on the left and the content of your page on the right it's normally a good way to do it. I say normally as this property wasn't initially designed for page layout purposes and, we're going to see, has a few minor drawbacks.

Let's reuse the structured HTML code we wrote a few chapters ago:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" />
        <title>Zozor - The Web Site</title>
    </head>

    <body>
        <header>
            <h1>Zozor</h1>
            <h2>Travel diaries</h2>
        </header>
        
        <nav>
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">Blog</a></li>
                <li><a href="#">Resume</a></li>
            </ul>
        </nav>
        
        <section>
            <aside>
                <h1>About the author</h1>
                <p>It's me, Zozor! I was born on 23 November 2005..</p>
            </aside>
            <article>                
                <h1>I'm a great traveller</h1>
                <p>Bla bla bla bla (article text)</p>
            </article>
        </section>
        
        <footer>
            <p>Copyright Zozor - All rights reserved

            <a href="#">Contact me!</a></p>
        </footer>
        
    </body>
</html>

Remember that without CSS the page layout looks like the figure below.

An HTML page without CSS
An HTML page without CSS

We're going to try to place the menu on the left and the rest of the text on the right. To do this, we'll float the menu to the left and leave the rest of the text to place itself on the right.

We want the menu to be 150 pixels wide. We're also going to add a black border around the menu and a blue border around the body (using the<section>tag) to make them stand out:

nav
{
    float: left;
    width: 150px;
    border: 1px solid black;
}

section
{
    border: 1px solid blue;
}

Here's the result in the figure below. We're not quite there yet.

The menu is correctly positioned but stuck to the text
The menu is correctly positioned but stuck to the text

There are two flaws (apart from the fact that it's still not very pleasing to the eye):

  • The page body text touches the edge of the menu. It needs a slight margin…

  • But more annoying still: the rest of the text flows... under the menu!

Although we want the footer ("Copyright Zozor") to be placed at the bottom under the menu, we'd like the entire page body to be a single block on the right.

To solve these two problems in one go, we need to add an outer margin to the left of our<section>, and this margin must also be greater than the menu width. If our menu is 150 px wide, we're going, for example, to give our page section a left outer margin of 170 px (figure below), in line 10.

nav
{
    float: left;
    width: 150px;
    border: 1px solid black;
}

section
{
    margin-left: 170px;
    border: 1px solid blue;
}
The page body is properly aligned to the right of the menu
The page body is properly aligned to the right of the menu

There you are, the page content is now properly aligned.

Changing your items with display

I'm now going to show you how to change the rules of CSS (hhhuh...). Hang on!

CSS has a very powerful property:display. It's able to change any item on your page from one type to another. With this magical property, I can, for example, make my links (originally of the inline type) appear in block form:

a
{
    display: block;
}

The links will then be positioned one below the other (like normal blocks) and you will then be able to change their dimensions!

Here are a few of the main values that thedisplayproperty can take in CSS (there are other ones as well):

Value

Examples

Description

inline

<a>,<em>,<span>

Items of a line. Are located next to each other.

block

<p>,<div>,<section>

Items in the form of blocks. Are located one below the other and can be resized.

inline-block

<select>,<input>

Items positioned next to each other (like inlines), but can be resized (like blocks).

none

<head>

Items not displayed.

You can thus decide to completely hide a page item using this property. For example, if I want to hide the items belonging to the "secret" class, I would write:

.secret
{
    display: none;
}

And what is this new strange type,inline-block? Is a mix?

Yes, this type of item is in fact a combination of inlines and blocks. It's the best of both worlds in a way: items are displayed side by side and can be resized.

Very few tags are displayed as default in this way and mainly involves form items (such as<input>) that we'll find out about a bit later on. However, using thedisplayproperty, we're going to be able to change other tags intoinline-block, which will help us to build our design.

Inline-block positioning

The steps involved in positioning floating objects may sometimes be a bit tricky on complex websites. As soon as there's any more than a simple menu to be formatted, you may have to resort toclear: both;tags that quickly complicate the page code.

While floating positioning remains by far the positioning method mostly widely used on the Web today, other techniques are available although very few webmasters know this. One of these surprisingly powerful techniques has gone unnoticed by web designers even though it has been around since CSS 2.1, in other words, for more than ten years! It involves changing your items intoinline-blockusing thedisplayproperty.

Here are a few little reminders about inline-block type items:

  • They are positioned next to each other (which is exactly what we want to position our menu and the body of our page!).

  • Specific dimensions can be assigned to them (there again, exactly what we want!).

We're going to change the two items we want to place side by side into inline-block items: the browsing menu and the page center section.

nav
{
    display: inline-block;
    width: 150px;
    border: 1px solid black;
}

section
{
    display: inline-block;    
    border: 1px solid blue;
}

The result is shown in the figure below.

The menu and the body are side by side… but positioned at the bottom!
The menu and the body are side by side… but positioned at the bottom!

Yuk!
This is not quite what we wanted. In fact, it's normal: the inline-block items are positioned on the same baseline, at the bottom below.

Fortunately, having changed the items into inline-block, we can use a new property, normally reserved for tables:vertical-align. This property is used to change the vertical alignment of items. Here are some of the possible values this property can take:

  • baseline: aligns the base of the item with the base of the parent element (default);

  • top: aligns at the top;

  • middle: centers vertically;

  • bottom: aligns at the bottom;

  • (value in px or as a %): aligned at a certain distance from the baseline.

We then only have to top align our items (lines 6 and 13), and there you are (figure below)!

nav
{
    display: inline-block;
    width: 150px;
    border: 1px solid black;
    vertical-align: top;
}

section
{
    display: inline-block;    
    border: 1px solid blue;
    vertical-align: top;
}
The menu and the body are aligned at the top and side by side
The menu and the body are aligned at the top and side by side

And that's all there is to it! No need to bother with margins, no risk of the text flowing under the menu... In short, it's perfect!

… What? Sorry, I've just heard that a certain browser is playing up...

inline-blockand compatibility with Internet Explorer

inline-blockpositioning is fully understood by Internet Explorer from IE8 onwards.

For older versions, IE6 and IE7 in particular, inline-block positioning works... but only on those items that were initially inline!

Fortunately, we can solve this problem with a small "workaround": if the browser is IE6 or IE7, you convert the item into inline and change its behavior by giving it the layout (by assigning it with the propertyzoom: 1;). The item can then be resized.

To start with, you'll have to create a second special CSS style sheet for Internet Explorer 6 and 7. For this purpose, we're going to use a conditional comment we've already seen before, that will only be read by IE6 and IE7:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <link rel="stylesheet" href="style.css" />
        <!--[if lte IE 7]>
        <link rel="stylesheet" href="style_ie.css" />
        <![endif]-->

        <title>Zozor - The Web Site</title>
    </head>

If the browser is IE6 or IE7, a second Cascading Style Sheet (CSS),style_ie.css, will be loaded and added to the first one. It will contain all our "workarounds" to solve the problems related to old versions of Internet Explorer to ensure that our website will be displayed properly everywhere, even on dinosaure software ;-) .

Instyle_ie.css, simply add the following code:

nav, section
{
    display: inline;
    zoom: 1;
}

There you go, that's all. In our regular CSS (style.css), you can carry on usinginline-blockas before. Those who are running IE6 or IE7 will also read this slightly special code, which will allow them to obtain the same visual result

Absolute, fixed and relative positioning

There are a few other fairly specific techniques used to accurately position items on the page:

  • Absolute positioning: allows us to place an item anywhere on the page (top left, bottom right, centered, etc.).

  • Fixed positioning: same as absolute positioning, but this time the item remains visible, even if you go further down the page. It's similar to thebackground-attachment: fixed;principle (if you still remember it).

  • Relative positioning: allows the item to be offset relative to its normal position.

You first have to choose between the three positioning modes available. For this purpose, you use the CSSpositionproperty giving it one of these values:

  • absolute: absolute positioning;

  • fixed: fixed positioning;

  • relative: relative positioning.

We're going to examine each of these positioning modes.

Absolute positioning

Absolute positioning allows you to place an item really anywhere on the page. To position an item absolutely, you enter:

element
{
    position: absolute;
}

But this is not enough! Although we specified absolute positioning, we have to say where we want the block to be positioned on the page.
For this purpose, we're going to use four CSS properties:

  • left: position relative to the left of the page;

  • right: position relative to the right of the page;

  • top: position relative to the top of the page;

  • bottom: position relative to the bottom of the page.

You can give them a value in pixels, such as 14px, or a percentage value, such as 50%.

If this is still not clear to some of you, the figure below should help you to understand.

Positioning of absolute items
Positioning of absolute items

With this property, you should be able to position your block correctly.

You thus have to use thepositionproperty and at least one of the four properties above (top,left,rightoubottom). If you enter, for example:

element
{
    position: absolute;
    right: 0px;
    bottom: 0px;
}

... this means that the block must be positioned right at the bottom on the right (0 pixels relative to the right of the page, 0 relative to the bottom of the page).

If we try to put our<nav>block at the bottom right of the page, we get the same result as in the figure below.

The menu is positioned in the bottom right-hand corner of the screen
The menu is positioned in the bottom right-hand corner of the screen

You can, of course, add an inner margin (padding) to the menu to move it away from its border slightly.

Absolutely positioned items are placed above the remaining items of the page! In addition, if you position two items absolutely in the same place, they may overlap. In this case, use thez-indexproperty to specify which item should appear on top of the other items.

element
{
    position: absolute;
    right: 0px;
    bottom: 0px;
    z-index: 1;
}
element2
{
    position: absolute;
    right: 30px;
    bottom: 30px;
    z-index: 2;
}

The item having the highestz-indexvalue will be placed on top of the others, as shown in the figure below.

Positioning of absolute items
Positioning of absolute items

Fixed positioning

The principle is exactly the same as for absolute positioning, except that this time the block stays fixed in its position, even if you go further down the page.

element
{
    position: fixed;
    right: 0px;
    bottom: 0px;
}

Try it and see the result. You'll see that the menu in this case stays displayed at the bottom right even if you move further down the page (figure below).

Relative positioning

Relative positioning is more tricky and can quickly become difficult to use. This type of positioning allows you to make "adjustments": the item is offset from its initial position.

Let's take, for example, an important text located between two tags<strong>. To start with, I'll place it on a red background so we can identify it better:

strong
{
   background-color: red; /* Red background */
   color: yellow; /* Yellow text */
}

This time, the procedure I showed you earlier on for absolute and fixed positions no longer works. Why? Because the origin has changed: the coordinates point (0, 0) is no longer located at the top left of your window as was the case earlier. No, this time the origin is located at the top left... of your item's current position.

A bit twisted, isn't it? It's the principle of the relative position. The diagram in the figure below should help you understand where the origin of the points is located.

Relative position origin
Relative position origin

So, if you enterposition: relative;and apply one of the propertiestop,left,rightoubottom, the text on red background will move relative to its current position.

Let's take an example: I want my text to be offset by 55 pixels to the right and 10 pixels downwards. I'm thus going to ask for it to be offset by 55 pixels from the "left edge" and 10 pixels from the "top edge" (lines 6 to 8):

strong
{
   background-color: red;
   color: yellow;
   
   position: relative;
   left: 55px;
   top: 10px;
}

The text is then offset from its initial position, as shown in the figure below.

This text is offset
This text is offset

Summing up

  • CSS is used for the page layout of a website. Several techniques are available to us.

  • Floating positioning (using thefloatproperty) is one of the most widely used techniques at present. It allows you, for example, to position a menu on the left or right of the page. This property was not originally designed for this purpose, however, and it's better to avoid this technique, if possible.

  • inline-blockpositioning involves assigning aninline-blocktype to our items through thedisplayproperty. They behave like inlines (positioning from left to right) but can be resized like blocks (usingwidthandheight). This technique is preferable to floating positioning.

  • Absolute positioning allows you to position an item wherever you want on the page, to the nearest pixel.

  • Fixed positioning is similar to absolute positioning but the item will remain visible even if you go further down the page.

  • Relative positioning allows a block to be offset relative to its normal position.

  • An item A, absolutely positioned inside another item B (itself positioned in absolute, fixed or relative mode), will be positioned relative to this item B, and not relative to the top left corner of the page.

Example of certificate of achievement
Example of certificate of achievement