CSS Center text (Horizontal and Vertical) inside a DIV block
I have a
div set to
90px height and width) and I have some text inside.
I need the text to be aligned in the center both vertically and horizontally.
I have tried
text-align:center, but it doesn’t do the horizontal part so I tried
vertical-align:middle but it didn’t work.
Common techniques as of 2014:
### 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.
Methods 4 and 5 aren’t the most reliable. Go with one of the first 3.