Positioning in CSS

Positioning in CSS

When we want to design some complex layouts, we need to change the document flow and modify the default settings.

In order to implement such complex layouts, we have the concept of positioning in CSS. Here in CSS, we have the position property.

The position property specifies the type of positioning used for an element.

We have five different values for the position property:-

  1. static
  2. relative
  3. absolute
  4. fixed
  5. sticky

CSS Syntax:-

position: static | relative | absolute | fixed | sticky | initial | inherit;

The detailed explanation of the CSS positioning property are as follows:- static:- It is the default value. The elements render in the order as they appear in the document flow.

relative:-

The element is positioned relative to its normal position.

<style>
.right {
  position: relative;
  left: 50px;
}
</style>
</head>
<body>
<h1>The position Property:relative</h1>
<p>Relative positioning moves an element RELATIVE to its original position.</p>
<h2 class="right">This heading is moved 50 px right according to its normal position</h2>
</body>

image.png

absolute:-

The element is positioned relative to its first positioned ancestor element.

<style>
h2 {
  position: absolute;
  left: 100px;
  top: 150px;
}
</style>
</head>
<body>
<h1>The position Property: absolute</h1>
<h2>This is a heading with an absolute position</h2>
<p>With absolute positioning, an element can be placed anywhere on a page.</p>
</body>

image.png

fixed:-

The element is positioned relative to the browser window.

<style>
h2 {
  position: fixed;
  left: 100px;
  top: 150px;
}
</style>
</head>
<body>
<h1>The position Property: fixed</h1>
<h2>This is a heading with an fixed position</h2>
</body>

image.png

sticky:-

The element is positioned based on the user's scroll position.

<style>
h2 {
  position: fixed;
  left: 100px;
  top: 150px;
}
</style>
</head>
<body>
<h1>The position Property: sticky</h1>
<h2>This is a heading with an sticky position</h2>
</body>

image.png

static:-

HTML elements are positioned static by default. Static positioned elements are not affected by the top, bottom, left, and right properties.

<style>
h2 {
  position: static;
  left: 100px;
  top: 150px;
}
</style>
</head>
<body>
<h1>The position Property: static</h1>
<h2>This is a heading with an static position</h2>
</body>

image.png

The example below shows the detailed visualization of the positioning of elements in CSS.

Hope you liked this article. Happy Learning!!!