CSS Positioning
CSS positioning allows you to control the placement of elements on a webpage. There are five primary position values: static, relative, absolute, fixed, and sticky. Each one behaves differently in terms of how the element is placed on the page.
1. Static Positioning (Default)
- Default behavior: Elements are positioned according to the normal flow of the document (top-to-bottom).
- Cannot be adjusted using top, right, bottom, or left.
div { position: static;}2. Relative Positioning
- Relative to its normal position: The element is first placed according to the normal flow, and then adjusted by the specified values of top, right, bottom, or left.
div { position: relative; top: 20px; /* Moves the element 20px down */ left: 10px; /* Moves the element 10px to the right */}3. Absolute Positioning
- Positioned relative to the nearest positioned ancestor (i.e., an element with relative, absolute, or fixed positioning).
- If no ancestor is positioned, it’s positioned relative to the
<html>element.
div { position: absolute; top: 50px; /* 50px from the top of the parent/ancestor */ left: 100px; /* 100px from the left of the parent/ancestor */}4. Fixed Positioning
- Positioned relative to the viewport: The element stays in the same position even when the page is scrolled.
div { position: fixed; top: 0; right: 0; /* Fixed at the top-right corner of the viewport */}5. Sticky Positioning
- Acts like relative positioning until the element reaches a defined scroll position, then becomes “stuck” to that position as the page scrolls.
div { position: sticky; top: 0; /* Sticks to the top of the viewport once you scroll past it */}