CSS Positioning

CSS positioning property sets how an element is positioned in a document. For example:

.element {
  position: relative;
  top: 30px;
}

CSS Positioning– values

static:

every element has a static position by default, so the element will stick to the normal page flow. So if there is a left/right/top/bottom/z-index set then there will be no effect on that element.

relative:

an element’s original position remains in the flow of the document, just like the static value. But now left/right/top/bottom/z-index will work. The positional properties “nudge” the element from the original position in that direction.

absolute:

the element is removed from the flow of the document and other elements will behave as if it’s not even there whilst all the other positional properties will work on it.

fixed:

the element is removed from the flow of the document like absolutely positioned elements. In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.

sticky (experimental):

the element is treated like a relative value until the scroll location of the viewport reaches a specified threshold, at which point the element takes a fixed position where it is told to stick.

inherit:

the position value doesn’t cascade, so this can be used to specifically force it to, and inherit the positioning value from its parent.

CSS Positioning-sticky

CSS sticky value is like a compromise between the relative and fixed values. t allows you to position an element relative to anything on the document and then, once a user has scrolled past a certain point in the viewport, fix the position of the element to that location so it remains persistently displayed:

div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  padding: 5px;
  background-color: skyblue;
  border: 2px solid red;
}

CSS Positioning-relative

We will learn to position an element relevant to its normal position:

h2.pos_left {
  position: relative;
  left: -20px;
}

h2.pos_right {
  position: relative;
  left: 40px;
}