Forum Moderators: not2easy
Next up as a solution would be to use absolute positioning. A few things to know:
Absolute positioning works relative to a box that's either defined by the closest parent that has "position", or the viewport if none such parent exists.
So, how do you center in that reference? The first way is to use auto margins just as we do horizontally: set the top and bottom margins to auto, and set the height. In addition: set top and bottom to 0. [example1 below]
That does the trick in standards compliant browsers, however you need more for legacy IE versions: either something to teach it how to do things (like e.g. IE7.js, or either an alternate method for the conditional comment or so.
As alternate method one can put the top (or bottom, works there just as well) at 50%, in the middle. And then move it all back up with half the height using a negative margin. [example2 below]
But can't we do anything with that vertical align ?
You can increase the line-height of a text and vertically align the text in that line [example3]. If you add things like an image, it too can react to vertical alignment [example4]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>untitled</title>
<style type="text/css">
* {
padding:0;
margin:0;
}
html {
background-color: #ccc;
height: 100%;
}
body {
background-color: white;
width: 770px;
margin: 0 auto;
min-height: 100%;
}
.example1, .example2 {
height: 200px;
background-color: yellow;
position: relative;
}
.example1 p {
background-color: orange;
height: 1.2em;
margin: auto 0;
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.example2 p {
background-color: green;
height: 1.2em;
position: absolute;
top: 50%;
margin-top: -0.6em; /* half the height */
width: 100%;
}
.example3, .example4 {
background-color: yellow;
line-height: 200px;
vertical-align: middle;
}
.example4 img{
height: 100px;
width: 150px;
vertical-align: middle;
}
</style>
</head>
<body>
<p>ipso</p>
<div class="example1">
<p>I wanna be centered vertically</p>
</div>
<p>ipso</p>
<div class="example2">
<p>I wanna be centered vertically</p>
</div>
<p>ipso</p>
<p class="example3">I wanna be centered vertically</p>
<p>ipso</p>
<p class="example4">I wanna be centered vertically <img src="1.jpg" alt="image" /></p>
<p>ipso</p>
</body>
</html>