Skip to main content

CSS position: fixed

A fixed element is placed relative to the viewport, so it stays in the same spot even when the page is scrolled. Its final position is set with top, right, bottom, and left.

A fixed element does not leave a gap where it would normally have been.

Example

The fixed div sits in the lower-right corner and stays there as you scroll.

Prompt
An HTML page showing position: fixed. In an internal <style> block, give a div.fixed class position fixed, bottom 0, right 0, width 300px, and a 3px solid green border. Add a fixed div in the lower-right corner and enough page content to scroll, so the fixed element stays in place.
Output: complete HTML page

CSS position: absolute

An absolute element is placed relative to the nearest positioned ancestor (one with a position other than static). If there is no positioned ancestor, it uses the document body and moves with page scrolling.

Note: Absolute elements are removed from the normal flow and can overlap other elements.

Example

The absolute div is placed relative to its relative-positioned parent.

Prompt
An HTML page showing position: absolute inside a positioned ancestor. In an internal <style> block, make a div.relative parent with position relative, a width, height, and green border; and a div.absolute child with position absolute, top 80px, right 0, a smaller width and height, and a red border. Nest the absolute div inside the relative one so it is placed relative to the parent.
Output: complete HTML page

Positioning Text On an Image

You can also use positioning to place text on top of an image, in spots such as the top left, top right, bottom left, bottom right, or center. PromptCookbook links to a full example for each position.