What is the easiest way to align a div whose position is relative horizontally and vertically using CSS ? The width and the height of the div is unknown, i.e. it should work for every div dimension and in all major browsers. I mean center alignment.
I thought to make the horizontal alignment using:
margin-left: auto;
margin-right: auto;
like I did here.
Is this a good cross browser solution for horizontal alignment ?
How could I do the vertical alignment ?
Horizontal centering is only possible if the element’s
widthis known, else the browser cannot figure where to start and end.This is perfectly crossbrowser compatible.
Vertical centering is only possible if the element is positioned absolutely and has a known
height. The absolute positioning would however breakmargin: 0 auto;so you need to approach this differently. You need to set itstopandleftto50%and themargin-topandmargin-leftto the negative half of itswidthandheightrespectively.Here’s a copy’n’paste’n’runnable example:
That said, vertical centering is usually seldom applied in real world.
If the width and height are really unknown beforehand, then you’ll need to grab Javascript/jQuery to set the
margin-leftandmargin-topvalues and live with the fact that client will see the div quickly be shifted during page load, which might cause a “wtf?” experience.