Skip to main content

CSS Positioning

CSS positioning controls where elements are placed on a page. With it, you can override the normal document flow.


The CSS position Property

The position property sets the positioning type of an element. It can take these values:

  • static — the default. The element follows the normal document flow.
  • relative — the element is placed relative to its normal position.
  • fixed — the element is placed relative to the viewport.
  • absolute — the element is placed relative to the nearest positioned ancestor.
  • sticky — the element switches between relative and fixed depending on the scroll position.

Elements are then moved to their final spot with the top, bottom, left, and right properties.


CSS position: static

All HTML elements are static by default. A static element is not affected by the top, bottom, left, and right properties and always follows the normal flow of the page.

Example

The div uses position: static and stays in the normal flow.

Prompt
An HTML page showing position: static. In an internal <style> block, give a div.static class position static and a 3px solid green border. Add a div using it. A static element follows the normal page flow.
Output: complete HTML page

CSS position: relative

A relative element is placed relative to its normal position. Setting top, right, bottom, or left moves it away from that spot. The gap it leaves behind is not filled by other content.

Example

The div is shifted 30px to the right of its normal position.

Prompt
An HTML page showing position: relative. In an internal <style> block, give a div.relative class position relative, left 30px, and a 3px solid green border. Add a div using it. It shifts 30px right of its normal position.
Output: complete HTML page