CSS Position - static, relative, absolute, sticky, fixed

CSS offers several positioning options that allow you to control the placement of HTML elements on a web page. These positioning options are static, relative, absolute, sticky, and fixed. Each one serves a specific purpose. Let’s explore each of them with examples:

Static:

  • position: static; is the default positioning for HTML elements.
  • Elements with a static position are positioned according to the normal flow of the document.
  • Top, bottom, left, right, and z-index properties have no effect. Example:

<div style="position: static; border: 1px solid black;">
  This is a static element.
</div>

Relative:

- position: relative; allows you to adjust an element’s position relative to its normal position in the document flow.

  • You can use top, bottom, left, and right properties to move the element. Example:

`html

This is a relatively positioned element.
` ## Absolute:
  • position: absolute; removes the element from the normal flow and positions it relative to its nearest positioned ancestor (or the viewport if none is found).
  • It’s commonly used for creating overlays or pop-up elements. Example:

<div style="position: relative; border: 1px solid black;">
  This is a relatively positioned container.
  <div style="position: absolute; top: 10px; left: 10px; background-color: #f00;">
    This is an absolutely positioned element.
  </div>
</div>

Sticky:

  • position: sticky; is a unique positioning value that combines aspects of both relative and fixed positioning.
  • It behaves like relative positioning within its parent container until the element reaches a defined offset, after which it becomes fixed. Example:

<div style="height: 200px; overflow: auto;">
  <div style="position: sticky; top: 10px; background-color: #00f;">
    This is a sticky element.
  </div>
  <!-- Content that scrolls -->
</div>

Fixed:

  • position: fixed; positions an element relative to the viewport, so it stays in the same position even when the page is scrolled.
  • Commonly used for navigation bars or elements that should always be visible. Example:

<div style="position: fixed; top: 0; left: 0; background-color: #0f0;">
  This is a fixed element.
</div>

Remember that you can use these positioning values in combination with other CSS properties to create complex layouts and designs on your web page. The choice of positioning value depends on the specific requirements of your layout and design.

Previous
CSS Font Size - px, em, rem, vw, vh
Next
Pseudo Class - hover, focus, active and Pseudo Element - before, after