Center Align Elements

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container. The element will then take up the specified width, and the remaining space will be split equally between the two margins. You still can specify margin-top and margin-bottom.

Note: Center aligning has no effect if the width property is not set (or set to 100%).

.center {
    margin: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

Center Align Text

To just center the text inside an element, use text-align: center;

.center {
    text-align: center;
    border: 3px solid green;
}

<div class="box">
	<div class="center">Hello World</div>
</div>
Hello World

Center Vertically - Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding:

.paddingMiddle {
    padding: 70px 0;
    border: 3px solid green;
}

<div class="box">
	<div style="border: 2px solid green;" class="paddingMiddle">
		Only I can change my life. No one can do it for me.
	</div>
</div>
Only I can change my life. No one can do it for me.

Center Vertically - Using line-height

Another trick is to use the line-height property with a value that is equal to the height property.

.center {
    line-height: 200px;
    height: 200px;
    border: 3px solid green;
    text-align: center;
}

/* If the text has multiple lines, add the following: */
.center p {
    line-height: 1.5;
    display: inline-block;
    vertical-align: middle;
}

Here is an example -

<div class="box">
	<div style="border: 2px solid green; height: 100px; text-align: center; line-height: 100px;">
		Optimism is the faith that leads to achievement. Nothing can be done without hope and confidence.
	</div>
</div>
Optimism is the faith that leads to achievement. Nothing can be done without hope and confidence.

Center Vertically - Using position & transform

If padding and line-height are not options, a third solution is to use positioning and the transform property:

.center { 
    height: 200px;
    position: relative;
    border: 3px solid green; 
}

.center p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

With the new day comes, new strength and new thoughts.

vertical-align

The vertical-align property in CSS controls how elements set next to each other on a line are lined up.

img {
  vertical-align: middle;
}

In order for this to work, the elements need to be set along a baseline. As in, inline (e.g. , ) or inline-block (e.g. as set by the display property) elements.

Middle

Baseline

Top

Bottom

Other values that you can use are -

These values are very insignificant as they are used very rarely.