Featured image of post How to center a DOM element

How to center a DOM element

Center an element sometimes can be very confusing. It can be center horizontally, center vertically or center both horizontally and vertically in the same time. In this article, we will be discussed multiple approaches to center the element in different situation.

Text Align

The first method will be text-align: center;. This method is useful when you wanted to center horizontally the text inside the DOM element.

Text Align element

However, this method is useful when the width of the DOM element is 100% or equivalent to it’s parent element. In otherwords, the DOM element will no be centered it’s width is not 100%. To handle such case, we can use margin: 0 auto

Margin Auto

margin: 0 auto; will be useful when we specify the width for the DOM element and wanted to center them in the middle

Margin auto to center elemetn

Note: This method only can be used on block element. In other words, inline-element such as span will no be affected as it’s width will be just right fitted from it’s content

block element vs span element in margin auto center method


Flexbox allows us to either center horizontally, vertically or both at the same time.

Center Horizontally

In order to center the desired element horizontally by using flexbox, it first needed to be wrapped inside a flex element. Then we can use justify-content: center to center the DOM element. Learn more on justify-content property

Flexbox horizontally center DOM element

Center Vertically

Center the element vertically is relatively similar to center horizontally where instead of using justify-content: center, we can now use align-items: center to center it vertically. Learn more on align-items property

Flexbox vertically center DOM element

Position Relative & Absolute

The last method from this article to center the element is by using poition: relative and poition: absolute. Position absolute need to be wrapped under Position relative, otherwise it will consider body as it’s parent element. We can then adjust the value for left and top to allocate the position that we want. transform: translate(x,x) property will be recommended to use together with position absolute to allocate precise location.

Position absolute to center the element
Copy the code here


  • margin: 0 auto can be used when it’s a block element and specify value of width
  • Flexbox (display: flex)
    • justify-content: center to center horizontally
    • align-items: center to center vertically
    • Using both together will ceter the element right at the middle
  • position: absolute better to be wrapped under position: relative otherwise it will consider body as it’s parent
    • It’s a good practice to use transform: translate(x,x) to allocate the element precisely.
comments powered by Disqus