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; }
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>
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>
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>
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.
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.
Other values that you can use are -
text-top
Aligns the top of the element with the top of the parent element's fonttext-bottom
Aligns the bottom of the element with the bottom of the parent element's font.sub
Aligns the baseline of the element with the subscript-baseline of its parent. Like where a <sub> would sit.sup
Aligns the baseline of the element with the superscript-baseline of its parent. Like where a <sup> would sit.length
Aligns the baseline of the element at the given length above the baseline of its parent. (e.g. px, %, em, rem, etc.)These values are very insignificant as they are used very rarely.