CSS Positions

CSS Positions

CSS Positions


CSS positions allow us to specify how an element should be positioned on a page. There are four different position values that we can use:

  1. Static
  2. Relative
  3. Absolute
  4. Fixed

Static

The static position is the default position value. Elements with a static position are not positioned in any special way. They just flow onto the page in the order they appear in the HTML.

/* This element has a static position and will be positioned in 
the order it appears in the HTML */
.static-element {
  position: static;
}

Relative

An element with a relative position is positioned relative to its normal position. This means that you can use top, right, bottom, and left properties to move the element around on the page. However, the space that the element would have occupied in the normal flow of the page is still preserved.

/* This element has a relative position and will be positioned 10 pixels 
from the top and left of its normal position */
.relative-element {
  position: relative;
  top: 10px;
  left: 10px;
}

Absolute

An element with an absolute position is positioned relative to its nearest ancestor that has a position other than static. If there is no such ancestor, the element is positioned relative to the initial containing block.

/* This element has an absolute position and will be positioned 10 pixels 
from the top and left of its nearest non-static ancestor */
.absolute-element {
  position: absolute;
  top: 10px;
  left: 10px;
}

Fixed

An element with a fixed position is positioned relative to the browser window, and it stays in the same place even if the page is scrolled.

/* This element has a fixed position and will be positioned 10 pixels 
from the top and left of the browser window */
.fixed-element {
  position: fixed;
  top: 10px;
  left: 10px;
}

Example

Here is an example of how these position values can be used to create a simple layout for a page.

/* The header has a fixed position so it stays at the top of the page */
header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

/* The main content is positioned relative to its normal position, 
but is indented by 20 pixels */
main {
  position: relative;
  margin-left: 20px;
}

/* The sidebar has an absolute position, so it is positioned 20 pixels 
from the top and right of its parent element */
aside {
  position: absolute;
  top: 20px;
  right: 20px;
}

/* The footer is just a normal, static element that will be positioned 
in the order it appears in the HTML */
footer {
  position: static;
}

In conclusion, CSS positions allow us to specify how elements should be positioned on a page. The four position values - static, relative, absolute, and fixed - each have their own behavior and can be used to create a wide range of layouts.