Horizontal centering.
When the element to be centered is an inline element we use text-align
center on its parent.
When the element is a block level element we give it a width and set the left and right margins to a value of auto.
Vertical centering
The values for vertical-align
have meaning with respect to a parent inline element.
With a line of text the values are relative to the line-height
.
With a table cell the values are relative to the table-height-algorithm, which usually means the height of the row.
Unfortunately vertical-align
doesn’t apply to block-level elements like a paragraph inside a div.
Line-Height Method
Set a line-height
on the child element containing the text larger than its font-size
.
By default equal space will be given above and below the text and so the text will sit in the vertical center.
Only works for vertically centering a single line of text.
It’s often recommended to also set the height on the element with the same value given to the line-height. However this doesn’t seem to be necessary.
Be careful when using the shortcut for the font property. This method relies on you setting the line-height
as a value greater than the font-size
. When you use the font shortcut any property you don’t specifically set gets set to its default value. With line-height
that default is 1. If you use the font shortcut, just make sure to explicitly set the line-height
inside.
To vertically center an image with this approach, set the line-height
(taller than the image) on the parent instead and add vertical align: middle
to the child image.