CSS Position Fixed

The position: fixed property in CSS allows you to position an element relative to the viewport, regardless of scrolling. This means that the element will stay in the same position even if you scroll the page.

Basic Syntax

        
            selector {
   position: fixed;
   top: value;
   right: value;
   bottom: value;
   left: value;
}
        
    

top, right, bottom and left determine the distance of the element from the respective edges of the viewport.

Example

Try yourself
        
            div {
    position: fixed;
    top: 50px;
    left: 50px;

    width: 100px;
    height: 100px;
    background-color: red;
}
        
    

Stacking Contexts Basics

Example
Try yourself
        
            div.first {
    position: fixed;
    top: 150px;
    left: 150px;

    border-width: thin;
    border-style: solid;
    width: 200px;
    height: 200px;
    background-color: orange;
}
div.second {
    position: fixed;
    top: 155px;
    left: 155px;

    border-width: thin;
    border-style: solid;
    width: 200px;
    height: 200px;
    background-color: green;
}
div.third {
    position: fixed;
    top: 160px;
    left: 160px;

    border-width: thin;
    border-style: solid;
    width: 200px;
    height: 200px;
    background-color: red;
}
        
    

Use Cases

1. Header/Footer

Create a fixed header or footer that remains visible as the user scrolls.

2. Sidebar

Create a sidebar that stays visible while the main content scrolls.

3. Modal Dialog

Implement a modal dialog that stays centered on the screen regardless of scrolling.