DEV Community

Cover image for Understanding CSS Positioning
Rakshambika
Rakshambika

Posted on

Understanding CSS Positioning

When building web pages, controlling where elements appear on the screen is essential. CSS provides the position property, which allows developers to place elements precisely within a webpage layout.

Understanding CSS positioning is crucial for creating navigation bars, popups, sticky headers, sidebars, and modern UI components.

What is CSS Position?

The position property determines how an HTML element is positioned on a webpage.

selector {
position: value;
}

There are five main position values:

  1. static
  2. relative
  3. absolute
  4. fixed
  5. sticky

1. Static Position (Default)

Every HTML element is positioned as static by default.

.box {
    position: static;
}
Enter fullscreen mode Exit fullscreen mode

2. Relative Position

An element is positioned relative to its original position.

.box {
    position: relative;
    top: 20px;
    left: 30px;
}
Enter fullscreen mode Exit fullscreen mode

3. Absolute Position

An absolutely positioned element is removed from the normal document flow.

.box {
    position: absolute;
    top: 50px;
    left: 100px;
}
Enter fullscreen mode Exit fullscreen mode

4. Fixed Position

A fixed element stays in the same place even when the page scrolls.

.box {
    position: fixed;
    bottom: 20px;
    right: 20px;
}
Enter fullscreen mode Exit fullscreen mode

5. Sticky Position

Sticky positioning combines relative and fixed behavior.

.box {
    position: sticky;
    top: 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)