Fixed and sticky positioning
Definition and purpose
Fixed positioning is usually relative to the viewport; sticky positioning stays in flow and adjusts relative to a scrollport, constrained by its containing block.
Viewport control
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>#a { position: fixed; top: 10px; left: 20px; }</style> </head> <body> <div id="a">Sample A</div> <div id="b">Sample B</div> </body></html>A is relative to the viewport here.
Syntax and mental model
position: fixed; top: 0; right: 0 anchors a viewport control. position: sticky; top: 0 keeps a heading near the scrollport top when scrolling. Sticky requires a non-auto inset on the relevant axis and room to move. Transformed ancestors can alter the fixed reference.
Sticky heading
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; } #a { height: 100px; overflow: auto; } #child { position: sticky; top: 0; height: 30px; } #b { height: 300px; } </style> </head> <body> <div id="a"> <div id="child">Header</div> <div id="b">Long content</div> </div> </body></html>The header stays at the scrollport top after scrolling 60px.
Common mistakes
Sticky is not permanently fixed: check ancestor overflow and available travel. Avoid fixed controls that obscure focused content.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Absolute positioning and containing blocks. Next lesson: Stacking contexts and z-index.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fixed and sticky positioning — knowledge check
Five questions on fixed and sticky positioning.
What is fixed normally relative to?
Does sticky retain flow allocation?
What is needed for sticky movement on an axis?
What can alter the fixed reference?
Why inspect ancestor overflow?