Skip to content
Related Articles

Related Articles

4 Different Ways to Center an Element using CSS
  • Last Updated : 22 Feb, 2021

When we create a web page, we most probably have come across the issue to center an element. So let us take a look at 4 different ways to center an element using CSS:

  1. Using Flex
  2. Margin Property
  3. Grid Property
  4. Absolute Property

Now let’s have a look at how these respective properties work using example.

HTML Code:

Filename: index.html

HTML






<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
    <link rel="stylesheet" href="styles.css" />
</head>
  
<body>
    <div class="parent">
        <div class="child">
            This element is centered
        </div>
    </div>
</body>
  
</html>

In the above code, we have created a parent div and a child div. We will take a look on how to center the child div inside the parent div. A stylesheet titled styles.css has been linked to the file where we have defined the styles of the parent and child div.

Filename: styles.css 

CSS




.parent {
  height: 400px;
  width: 400px;
  background-color: red;
}
.child {
  height: 100px;
  width: 100px;
  background-color: blue;
}

Method 1: Using Flex We can use Flexbox in order to center the element. We can set the display property of parent div as flex and can easily center the children div using justify-context : center (horizontally) and align-items : center (vertically) properties.

CSS




.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

Method 2: Margin Property Another simple way to center a child div is to set it’s margin to auto and make the parent div display as grid.

CSS




.parent {
  display: grid;
}
.child {
  margin: auto;
}

Method 3: Grid Property A quite easy way to center elements is to use the grid property on the parent div and set the place-items: center.

CSS




.parent {
  display: grid;
  place-items: center;
}

Method 4: Absolute Property We can also use the position property to center the elements.

CSS




.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Output:

The output of all these ways will be the same which is shown below:

My Personal Notes arrow_drop_up
Recommended Articles
Page :