Skip to content
Related Articles

Related Articles

How to use the position property in CSS to align elements ?
  • Last Updated : 31 Mar, 2021

In this article, we will learn how to use the position property in CSS to align elements. We can align elements using position property using CSS with some helper property of it.

Approach: The position property is used to set the position of the element. We can align elements using position property with some helper property left | right | top | bottom, which is used to set the element’s coordinates. To align elements using position property, we set the element’s position, and then using helper property, we set the coordinates of the element.

Syntax:

position: static | relative | absolute | fixed | sticky

Example 1: Below is the implementation of the above approach that align element to the center.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .gfg-1{
            color: green;  
            background-color: rgb(216, 216, 216);  
        }  
        .gfg-2{
            background-color: rgb(199, 198, 198); 
            color: green;
            /* Make element to relative to its normal position */
            position: relative;
            /* This set cordinates of the element and align it to center */
            left: 600px;
        }
    </style>
</head>
<body>
    <div class="gfg-1" style="height: 200px;font-size: 50px;">
           GeeksforGeeks
     </div>
    <div class="gfg-2" style="height: 200px;font-size: 50px;">
           GeeksforGeeks
     </div>
</body>
</html>

Output:

  • Before positioning:

Before positioning

  • After positioning:

After positioning

Example 2: The absolute position takes the position according to the page because the absolute position takes the page as a parent. To make it according to the parent we have to add relative to the parent class. 

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .gfg-1{
            color: green;  
            background-color: rgb(216, 216, 216);  
        }  
        .gfg-2{
            background-color: rgb(199, 198, 198); 
            color: green;
            /* Make element to relative to its normal position */
            position: absolute;
            /* This set cordinates of the element*/
            left: 0px;
        }
        .parent{
            /* To make element relative */
            position: relative;
        }
    </style>
</head>
<body>
    <div class="parent" style="width: 50%;margin-left: 50px;">
        <div class="gfg-1" style="height: 200px;font-size: 50px;">
              GeeksforGeeks
        </div>
        <div class="gfg-2" style="height: 200px;font-size: 50px;">
              GeeksforGeeks
        </div>
    </div>
</body>
</html>

Output:

  • Before positioning:

Before positioning

  • After positioning:

After positioning




My Personal Notes arrow_drop_up
Recommended Articles
Page :