How to center align an element horizontally ?

Here are many options to center align an element vertically and horizontally. I will explain the three simplest methods here.

We have a container element that wraps the element which should be center. you can use a <div> element with a class or ID. Here I am using class.

Hence I have two elements, one is the parent and the second is the child, with some styles.

<div class="parentEle">
  <div class="childEle">Foo</div> 
</div>
.parentEle {  
	border: 1px solid black;
	height:300px;
	width: 300px;
}
.childEle{
	border: 1px solid red;
	height: 30px;
	width: 30px;
}

So, in above code we want to center align “childEle” div, below is some method to achive it.


Method 1 (using flex) – 
In this method we have to add some flex style on parent element

.parentEle {  
    border: 1px solid black;
    height:300px;
    width: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
}

Method 2 (using position and transform) – 

In this method, we add position:relative to the parent element and other styles to the child element.

.parentEle {  
    border: 1px solid black;
    height:300px;
    width: 300px;
    position: relative;
}
.childEle{
    border: 1px solid red;
    height: 30px;
    width: 30px;
    position: absolute;
    top: 50%;
    left:50%;
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

Method 3 (using grid) –

In this method you need to add style on parent elements 

.parentEle {  
    border: 1px solid black;
    height:300px;
    width: 300px;
    display: grid;
    place-items: center;
}

I hope this information is helpful to you.


7 comments on “How to center align an element horizontally ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 35,513 other subscribers

Follow bufixr.com

Copyright © BugFixr 2023-2024