CSS Position & Layout

We can use the position property to control the layout and position of an element on a webpage.

There are five different position values:

  • static - the default value (it does not need to be specified)
  • relative
  • fixed
  • absolute
  • sticky

I. position: static;

HTML elements have static value by default.

It doesn’t have special positioning qualities but keeps the element in a normal page flow.

II. position: relative;

If we set an element’s position relative, we can shift the element around the page relative to its original position.

We can adjust the position with the following properties:

  • top: moves the element down.
  • bottom: moves the element up.
  • left: moves the element right.
  • right: moves the element left.

Example: The following code will set H2 away from the left by 20 pixels and move it from the bottom of its original position by 20 px.

h2 {
  position: relative;
  left: 20px;
  bottom: 20px;
}

III. position: fixed;

position: fixed; will position the element relative to the viewport, so it always stays in the same place even if the page is scrolled.

Example: We can set our Navbar to be fixed at the top of the viewport.

.navbar {
  position: fixed;
  top: 0px;
  left: 0px;
}

IV. position: absolute;

position: absolute; allows us to position elements absolutely relative to their closet parent that has also been given a position property that is not static.

However, if an absolute positioned element has no positioned parents, it uses the document body and moves along with page scrolling.

#area-1 {
  position: absolute;
  left: 20px;
  top: 20px;
}

V. position: sticky;

Sticky is a combination of static and fixed.

It’s static at the beginning but becomes fixed when the scroll position on a page reaches a certain point.

#nav {
  position: sticky;
  top: 150px;
}

VI. Z-index

z-index property specifies the order of an element.

By default, all elements have a z-index of 0, so a positive z-index(1, 2, etc.) will place that element on top of the other elements.

z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky).

.navbar {
  z-index: 1;
}