How to center an element horizontally and vertically?
I was trying to center my tabs content vertically but when I add
inline-flex display, horizontal text-align disappears.
How can I make both text alignments x and y for each of my tabs?
### Approach 1 -
In supported browsers (most of them), you can use
left: 50% in combination with
translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.
- ### Approach 2 - Flexbox method:
In supported browsers, set the
display of the targeted element to
flex and use
align-items: center for vertical centering and
justify-content: center for horizontal centering. Just don’t forget to add vendor prefixes for additional browser support ( see example).
### Approach 3 -
In some cases, you will need to ensure that the
body element’s height is set to
For vertical alignment, set the parent element’s
100% and add
display: table. Then for the child element, change the
table-cell and add
For horizontal centering, you could either add
text-align: center to center the text and any other
inline children elements. Alternatively, you could use
margin: 0 auto, assuming the element is
### Approach 4 - Absolutely positioned
50% from the top with displacement:
This approach assumes that the text has a known height - in this instance,
18px. Just absolutely position the element
50% from the top, relative to the parent element. Use a negative
margin-top value that is half of the element’s known height, in this case -
### Approach 5 - The
line-height method (Least flexible - not suggested):
In some cases, the parent element will have a fixed height. For vertical centering, all you have to do is set a
line-height value on the child element equal to the fixed height of the parent element.
Though this solution will work in some cases, it’s worth noting that it won’t work when there are multiple lines of text - like this.