CSS - Position




CSS Position Property

A webpage has number of HTML elements and sometimes different elements need to align different kind of positioning for better page layout.

The CSS position property is used to specify the type of positioning for HTML Elements.

Type of CSS position properties

You can use four different positions for elements.

  • Static

  • Relative

  • Fixed

  • Absolute

We will learn about each of them with example.

CSS Position Static

This is the default position of HTML elements. A static position element according to the normal flow of the HTML page. There is no use of CSS top, bottom, left, and right properties if html element has static position.

Example

<!DOCTYPE html>
<html>
<head>
<style>
div.static {
    position: static;
    border: 2px solid #ff0000;
}
</style>
</head>
<body>
<h2>position: static;</h2>
<p>The CSS position property is used to specify the type of positioning for HTML Elements.</p>
<div class="static">
This div element has position: static;
</div>
</body>
</html>

Result

CSS Position Relative

HTML Element with Relative Position is positioned relative to its normal position. By default relative positioning works similar to static unless positioning you add some extra properties. You can use CSS top, bottom, left, and right properties to move element accordingly.

Example

<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
    position: relative;
    left: 25px;
    border: 4px solid #ffa500;
}
</style>
</head>
<body>
<h2>position: relative;</h2>
<p>An element with position: relative; is positioned relative to its normal position:</p>
<div class="relative">
This div element has position: relative;
</div>
</body>
</html>

Result

CSS Position Fixed

A CSS fixed element is positioned relative to the viewport or browser window. Fixed positioned element always stays in the same place even if you scroll page.

CSS Position Absolute

A CSS absolute element is positioned relative to the first parent element. If there is no parent element, position will be related to page. Therefore, absolute positioned element works like fixed but its position is related to nearest positioned parent (ancestor) instead of relative to the viewport window.