CSS

Last Updated: 10/18/2022

Position

  • Specifies the type of positioning method used for an element.
  • Possible values are
    • static
    • relative
    • fixed
    • absolute
    • sticky
  • Elements are then positioned using the top, bottom, left, and right properties after setting the position property other than static

Static

  • Elements are positioned static by default
  • Static positioned elements are not affected by the top, bottom, left, and right properties.
  • Always positioned according to the normal flow of the page
div {
	width: 100px;
	height: 100px;
	position: static;
}
	<div style="background-color:red">div 1</div>
	<div style="background-color:green">div 2</div>
	<div style="background-color:blue">div 3</div>

Relative

  • Positioned relative to its normal position.
  • 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.
.relative {
    position: relative;
    left: 100px;
}
	<div style="background-color:green" class="relative">div 2</div>

Absolute

  • Positioned relative to the nearest positioned parent
  • If an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
  • Absolute positioned elements are removed from the normal flow, and can overlap elements.
.absolute {
    position: absolute;
    left: 100px;
    top: 0px;
}

Auto width

.absolute {
    position: absolute;
    left: 10px;
    right: 100px;
    width: auto;
}

Fixed

  • Positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled.
  • A fixed element does not leave a gap in the page where it would normally have been located.
.fixed {
    position: fixed;
    top: 10px;
}

Sticky

  • Positioned based on the user's scroll position.
  • Toggles between relative and fixed, depending on the scroll position
  • Positioned relative until a given offset position is met in the viewport and then it sticks in place
.sticky {
    position: sticky;
    top: 0;
    background-color: lightblue;
    width: 100px;
    height: 100px;
}
<div class="sticky">sticky div</div>