Jul 152015

One of the most common tasks while designing web pages is centering elements both vertically and horizontally.

To center a block (div, p, h1, and so on) horizontally, the only thing you have to do is to apply a margin auto to it. For example,

You have to take into account that a width is necessary.

To center lines of text you can use text-align property. For example

If you want to center a block vertically, you can use the padding-top and padding-bottom properties with the same value. If you want to center a text line, you can use line-height

Another way would be to use a container block with a table display and a content block with a table-cell display and vertical alignment.

With CSS3 you can play with position, top and transform properties.

We can also use transform: translateY(-50%) instead of transform: translate(0, -50%) in the above example.

We can extend this method to center horizontally and vertically at the same time using margin-right and left properties.

Another way to center horizontally and vertically at the same time might be in same cases:

Sorry, the comment form is closed at this time.