CSS Positions

·

2 min read

Table of contents

No heading

No headings in the article.

Default mode-CSS position of an element is static.

  • New Position Context gets created whenever position property is other than static for that element .
  • top/bottom/left/right/z-index can be applied to that element.

1)Position-Relative

  • Element will be displaced according to itself and it's current position.
  • Will look like as static until applied with other properties like top/bottom etc.

2)Position-Absolute

HTML raycast-untitled (3).png

CSS

raycast-untitled (4).png

Output

css1.PNG

  • So absolute removes the element from the document flow and other elements if any below will take it's position.
  • Positions according to first no-static parent, if none would fallback to html. -Element will have a new position context created relative to parent.

Output when child 1 with absolute given top 0

css2.PNG

Output when container is given position relative on top of previous state.

css3.PNG

3)Fixed

Output State 1

.child1 {
  background-color: rebeccapurple;
  height: 30px;
  position:fixed;
  /* position: sticky; */
  /* top:0; */
}

container- static

css4.PNG

state 2 (uncommenting top 0)

css5.PNG

-Fixed is like normal absolute -It positions relative to screen size, not relative to parent -Element will be forever fixed at that position.

4)Sticky

-state1

.child1 {
  background-color: rebeccapurple;
  height: 30px;
  /* position: fixed; */
  position: sticky;
  /* top: 0; */
}

Element will behave as normal relative and there will be no changes until top/bottom specified.

state 2

.child1 {
  background-color: rebeccapurple;
  height: 30px;
  position: sticky;
  top: 0; 
}

Element will stay on top until it slides through all the elements below it in that parent container.

Thank you for reading :)