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:
- Using Flex
- Margin Property
- Grid Property
- Absolute Property
Now let’s have a look at how these respective properties work using example.
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.
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.
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.
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.
Method 4: Absolute Property We can also use the position property to center the elements.
The output of all these ways will be the same which is shown below: