The BLOG by ernest
Vertical and Horizontal Center Cheatsheet
-
Center a Text (inline element)
<div style="text-align:center"> <span>hello world</span> <!-- inline centered --> </div>
hello world -
Center a Block
<div style="width:5.5em; margin: auto"> <!-- block centered --> <span>hello world</span> </div>
hello world
-
Vertical Center a single line text
<div style="line-height:6.25em"><!-- single line vertical center - text by default align in the middle--> <span>hello world</span> </div>
hello world -
Vertical Center an image
<div style="line-height:6.25em"><!-- algin vertical image --> <img src="//dummyimage.com/50x50/f060f0/000000.png" style="vertical-align:middle"> </div>
-
Vertical Center using floater
<div> <div style="float:left; width:100%; height:50%; margin-bottom:-0.5em"></div>"><!-- darker area--> <div style="clear:both; height:1em"><!-- fixed height, floater bottom margin moves up--> Hello World </div> </div>
Hello World
-
Vertical Center multiple lines - using top and bottom padding
<div> <div style="padding:3em 0;"> Hello World<br>Centered in multiple lines<br>line number three<br>line number four </div> </div>
Hello World
Centered in multiple lines
line number three
line number four -
Vetical Center multiple lines - using table
<div style="display:table"> <div style="display:table-cell; vertical-align:middle"> Hello World<br>Centered in multiple lines </div> </div>
Hello World
Centered in multiple lines
line number three
line number four
-
Center BOTH Absolute positioning and negative margins
<!-- margin moves up and left half the width & height --> <div style="position:relative"> <div style="position:absolute; top:50%; left:50%; width:5em; height:1em; margin: -0.5em 0 0 -2.5em" <span>Hello World</span> </div> </div>
Hello World -
Center BOTH Absolute positioning and streaching
<div style="position:relative;"> <div style="position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; width:5em; height:1em"> Hello World </div> </div>
Hello World