Original
Demos of each of the methods below by clicking here.
Horizontal centering with CSS are rather easy. When the element was centered is a inline element we use Text-align Centeron its parent. When the element was a block level element we give width and set the "left" and "right" margins to auto.
With Text-align:center in mind, the most people look first to vertical-align in order to center things vertically.
Unfortunately vertical-align doesn ' t apply to block-level elements like a paragraph inside a Div, It applies to t Able cells and it works with some inline elements.
line-height Method
All we need to do are set a line-height on the element containing the text larger than its font-size.
<id= "parent"> <id= "Child" >Text here</div></Div >
{ line-height: 200px;}
The above works in all browsers, however it'll only works for a single line of text. If your text could wrap to a 2nd line need to use a different method. The value of 200px above is arbitrary. You can use any value of want as long as its larger than the font-size, that ' s been set.
Centering an Image with Line-height
What if the content are an image of want centered? Would this method work? The answer is yes and one additional line of CSS.
CSS Table Method
Above I mentioned that vertical-align applies to table cells which leads us to this method. We'll display our elements as table and table cells and then use the Vertical-align property to center the content.
Note: CSS tables is not the same as HTML tables.
6 ways to center CSS settings