CSS Position

Subject: css

CSS Position

The position property in CSS determines how an HTML element is placed in the document layout. It defines the positioning context and allows you to move elements using properties like top, right, bottom, and left.

Understanding position is essential for layout control, overlapping elements, and creating dynamic interfaces such as sticky headers, modals, or floating buttons.


Syntax


Types of Positioning

1. static

  • Default positioning.
  • Elements follow the normal document flow.
  • top, left, right, bottom have no effect.

2. relative

  • Moves the element relative to its original position.
  • Space in the layout is preserved.

3. absolute

  • Removed from normal flow.
  • Positioned relative to the nearest positioned ancestor (i.e., not static).
  • If none exists, it’s relative to the <html> (viewport).

4. fixed

  • Positioned relative to the viewport.
  • Does not move when scrolling.

5. sticky

  • Behaves like relative until a scroll threshold is met.
  • Then behaves like fixed.

Example: CSS Position Types


Key Takeaways

  • Use relative to offset elements while preserving layout space.
  • Use absolute to position elements inside a relatively-positioned container.
  • Use fixed for elements that remain visible while scrolling.
  • Use sticky for headers or elements that should stick after a certain scroll point.
  • absolute and fixed remove the element from the normal document flow.