What is position fixed in CSS: Explanation and Example
position: fixed in CSS means an element stays in the same place on the screen even when you scroll the page. It is fixed relative to the browser window, not the page content.How It Works
Imagine you have a sticky note on your computer screen that never moves no matter how much you scroll through your papers. position: fixed works like that sticky note. When you apply it to an element, that element stays visible in the same spot on the screen even if you scroll up or down the webpage.
This happens because the element is taken out of the normal page flow and positioned relative to the browser window itself, not the page content. So, it ignores scrolling and stays put.
Example
This example shows a box fixed at the top right corner of the screen. It stays visible even when you scroll the page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Position Fixed Example</title> <style> body { height: 2000px; /* Makes page scrollable */ margin: 0; font-family: Arial, sans-serif; } .fixed-box { position: fixed; top: 20px; right: 20px; background-color: #4CAF50; color: white; padding: 10px 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.3); } </style> </head> <body> <div class="fixed-box">I stay fixed!</div> <p>Scroll down to see the box stay in place.</p> </body> </html>
When to Use
Use position: fixed when you want something to always be visible on the screen, no matter how much the user scrolls. Common uses include:
- Sticky navigation menus or headers
- Back-to-top buttons
- Floating action buttons
- Chat widgets or notifications
It helps keep important controls or information accessible without scrolling back to the top.
Key Points
- Fixed elements stay in place relative to the browser window.
- They do not move when the page scrolls.
- They are removed from the normal page flow, so other elements behave as if they are not there.
- Use
top,right,bottom, andleftto position fixed elements. - Be careful not to cover important content unintentionally.
Key Takeaways
position: fixed keeps an element visible in the same spot on the screen during scrolling.top, right, bottom, and left CSS properties.