CSS Positioning

Use CSS positioning to specify precisely where an element should be located on the page.

The term "CSS positioning" refers to using CSS to position elements on your HTML page. CSS allows you to position any element precisely where you want it. You can specify whether you want the element positioned relative to its natural position in the page or absolute based on its parent element.

Absolute positioning can be very useful for creating advanced layouts and cool visual effects such as overlapping elements to present a layered effect.

Relative Positioning

To determine whether the element will be positioned relatively or absolutely, you use the position property.

To perform relative positioning in CSS you use position:relative; followed by the desired offset from either top, right, bottom or left.

This example offsets the element 80 pixels from the left of where it would have been. If we had specified top, it would appear 80 pixels below where it would have been. It's important to note that other elements are not affected by this element's offset. Therefore, overlapping may occur.

Absolute Positioning

To perform absolute positioning in CSS you again use the position property. Only, this time you use use position:absolute; followed by the desired offset.

<!DOCTYPE html>
<title>Example</title>
<style>
  div {
    position: absolute;
    top: 100px;
    left: 60px;
    background-color: gold;
    width: 90px;
    padding: 20px;
  }
</style>

<div>
  This div is absolutely positioned 100 pixels from the top and 60 pixels from the left of its containing block.
</div>

Try it with the Online Editor

Fixed Positioning

Fixed positioning allows you to fix the position of an element to a particular spot on the page - regardless of scrolling.

<!DOCTYPE html>
<title>Example</title>
<style>
  .absolute {
    position: absolute;
    top: 500px;
    left: 60px;
    height: 2000px;
    background-color: limegreen;
  }
  .fixed {
    position: fixed;
    top: 10px;
    left: 10px;
    background-color: gold;
    width: 90px;
    padding: 20px;
  }
</style>

<div class="absolute">
This tall div is absolutely positioned 500 pixels from the top and 60 pixels from the left of its containing block.
</div>


<div class="fixed">
  This div is using a fixed position of 100 pixels from the top and 60 pixels from the left of its containing block. When this page scrolls, this box will remain in a fixed position - it won't scroll with the rest of the page. Go on - SCROLL!
</div>

Try it with the Online Editor