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.
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
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
Flexbox
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
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
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.
Copy the code here
Summary
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 horizontallyalign-items: center
to center vertically- Using both together will ceter the element right at the middle
position: absolute
better to be wrapped underposition: 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.
- It’s a good practice to use