position

In order to make more complex layouts, we need to discuss the position property. It has a bunch of possible values, and their names make no sense and are impossible to remember. Let's go through them one by one, but maybe you should bookmark this page too.

static

.static {
  position: static;
}
<div class="static">

static is the default value. An element with position: static; is not positioned in any special way. A static element is said to be not positioned and an element with its position set to anything else is said to be positioned.

</div>

relative

.relative1 {
  position: relative;
}
.relative2 {
  position: relative;
  top: -20px;
  left: 20px;
  background-color: white;
  width: 500px;
}
<div class="relative1">

relative behaves the same as static unless you add some extra properties.

</div>
<div class="relative2">

Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.

</div>

fixed

<div class="fixed">

Hello! Don't pay attention to me yet.

</div>

A fixed element is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. As with relative, the top, right, bottom, and left properties are used.

I'm sure you've noticed that fixed element in the lower-right hand corner of the page. I'm giving you permission to pay attention to it now. Here is the CSS that puts it there:

.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 200px;
  background-color: white;
}

A fixed element does not leave a gap in the page where it would normally have been located.

Mobile browsers have surprisingly shaky support for fixed. Learn more about the situation here.

absolute

absolute is the trickiest position value. absolute behaves like fixed except relative to the nearest positioned ancestor instead of relative to the viewport. If an absolutely-positioned element has no positioned ancestors, it uses the document body, and still moves along with page scrolling. Remember, a "positioned" element is one whose position is anything except static.

Here is a simple example:

.relative {
  position: relative;
  width: 600px;
  height: 400px;
}
.absolute {
  position: absolute;
  top: 120px;
  right: 0;
  width: 300px;
  height: 200px;
}
<div class="relative">

This element is relatively-positioned. If this element was position: static; its absolutely-positioned child would escape and would be positioned relative to the document body.

<div class="absolute">

This element is absolutely-positioned. It's positioned relative to its parent.

</div>
</div>

This stuff is tricky, but it's essential to creating great CSS layouts. On the next page we'll use position in a more practical example.

  • Creative Commons License