📍

How to Position Elements with CSS

HTML/CSSIntermediate

Learn static, relative, absolute, fixed, and sticky positioning.

Code Example

HTML/CSS
<!DOCTYPE html>
<html>
<head>
  <title>CSS Positioning</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; }
    
    .container {
      position: relative;
      width: 400px;
      height: 300px;
      background: #f3f4f6;
      border: 2px solid #374151;
      margin: 20px 0;
    }
    
    /* Static (default) */
    .static {
      position: static;
      background: #3b82f6;
      color: white;
      padding: 10px;
    }
    
    /* Relative - offset from normal position */
    .relative {
      position: relative;
      top: 20px;
      left: 20px;
      background: #10b981;
      color: white;
      padding: 10px;
    }
    
    /* Absolute - relative to positioned ancestor */
    .absolute {
      position: absolute;
      top: 10px;
      right: 10px;
      background: #f59e0b;
      color: white;
      padding: 10px;
    }
    
    /* Fixed - relative to viewport */
    .fixed {
      position: fixed;
      bottom: 20px;
      right: 20px;
      background: #ef4444;
      color: white;
      padding: 15px;
      border-radius: 5px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    }
    
    /* Sticky - hybrid of relative and fixed */
    .sticky {
      position: sticky;
      top: 0;
      background: #8b5cf6;
      color: white;
      padding: 15px;
      margin-bottom: 20px;
    }
    
    .scroll-content {
      height: 200px;
      overflow-y: scroll;
      background: #e5e7eb;
      padding: 10px;
    }
  </style>
</head>
<body>
  <h1>CSS Positioning Demo</h1>
  
  <h2>Position Types</h2>
  
  <div class="container">
    <div class="static">Static (default)</div>
    <div class="relative">Relative (offset)</div>
    <div class="absolute">Absolute (top-right)</div>
  </div>
  
  <h2>Sticky Positioning</h2>
  <div class="sticky">I stick to the top when scrolling!</div>
  <div class="scroll-content">
    <p>Scroll down to see the sticky element in action...</p>
    <p>Content line 2</p>
    <p>Content line 3</p>
    <p>Content line 4</p>
    <p>Content line 5</p>
    <p>Content line 6</p>
    <p>Content line 7</p>
    <p>Content line 8</p>
  </div>
  
  <div class="fixed">
    Fixed Position (bottom-right)
  </div>
</body>
</html>

Explanation

Position types: static (default), relative (offset from normal), absolute (relative to positioned ancestor), fixed (relative to viewport), sticky (hybrid). Use top, right, bottom, left to offset.

Related Tutorials