Horizontal centering is only possible if the element's width
is known, else the browser cannot figure where to start and end.
#content {
width: 300px;
margin: 0 auto;
}
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 break margin: 0 auto;
so you need to approach this differently. You need to set its top
and left
to 50%
and the margin-top
and margin-left
to the negative half of its width
and height
respectively.
Here's a copy'n'paste'n'runnable example:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2935404</title>
</head>
<style>
#content {
position: absolute;
width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-left: -150px; /* Negative half of width. */
margin-top: -100px; /* Negative half of height. */
border: 1px solid #000;
}
</style>
<body>
<div id="content">
content
</div>
</body>
</html>
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-left
and margin-top
values and live with the fact that client will see the div quickly be shifted during page load, which might cause a "wtf?" experience.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…