SmartCodingTips

CSS Positioning

The position property in CSS allows you to control how elements are placed on the page. It works alongside properties like top, right, bottom, and left to precisely move elements.

1. static (default)

The default position. Elements are placed in the normal document flow.


.element {
    position: static;
}
            

2. relative

The element is positioned relative to its normal position. You can nudge it using top, left, etc.


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

3. absolute

Positioned relative to the nearest positioned ancestor (not static). If none, it's relative to the viewport.


.container {
    position: relative;
}

.child {
    position: absolute;
    top: 10px;
    right: 10px;
}
            

4. fixed

The element is positioned relative to the browser window. It stays in place during scroll.


.header {
    position: fixed;
    top: 0;
    width: 100%;
}
            

5. sticky

The element toggles between relative and fixed, based on the user's scroll position.


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

6. z-index

Controls the stacking order of overlapping elements. Higher values appear on top.


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

Conclusion

Understanding CSS positioning is essential for creating complex layouts. Combine positioning types with z-index and layout strategies like flexbox or grid for powerful control.