learn2kode.in

CSS Positioning

CSS positioning controls how elements are placed on a webpage. It defines the layout behavior and determines how elements interact with each other visually.

There are five main position values in CSS:

1. static (Default Positioning)

.element {
  position: static;
}

2. relative

.element {
  position: relative;
  top: 10px;
  left: 20px;
}

3. absolute

.element {
  position: absolute;
  top: 20px;
  right: 10px;
}

4. fixed

.element {
  position: fixed;
  bottom: 20px;
  right: 20px;
}

5. sticky

.element {
  position: sticky;
  top: 0;
}

CSS Position Properties

Once an element has a position value (other than static), you can use:

Property Description
top Offset from the top edge
right Offset from the right edge
bottom Offset from the bottom edge
left Offset from the left edge
z-index Controls stacking order (front/back)

z-index

Controls which element appears in front when elements overlap.

.front {
  position: absolute;
  z-index: 10;
}

.back {
  position: absolute;
  z-index: 1;
}

When to Use Each Position Type

Position Type Best Use Case
static Default layout, no special positioning
relative Slight adjustments, anchors for absolute children
absolute Popups, tooltips, exact placements
fixed Sticky navigation, floating elements
sticky Headers that stick while scrolling