问题
I am trying to make vertical-aligned div in relation to auto height div.
It is a little bit hard to explain so I have screenshot that will explain everything:

The orange div is the container.
The blue div is 2nd container inside the main container.
The green div is the vertical-aligned div which should be aligned in relation to the blue one.
I have no idea how to make this work. I want it to be cross browser (ie6+, ff & chrome).
Thank you very much!
回答1:
See: http://jsfiddle.net/thirtydot/aeFrH/
CSS:
#container {
width: 748px;
background: orange;
}
#container-inside {
width: 500px;
background: cyan;
}
#aligned {
width: 248px;
background: green;
}
#container-inside, #aligned {
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
}
HTML:
<div id="container">
<div id="container-inside">
Some<br />
content<br />
is<br />
in<br />
here.<br />
</div><div id="aligned">
Aligned.
</div>
</div>
回答2:
For this answer I have assumed that both the blue as the green divs have a dynamic height.
In order to calculate the correct offset of the green div we can not use CSS. CSS doesn't allow us to position an element using the data of another element.
Instead, we need to calculate the offset ourselves which requires a client-side language. Time to embrace Javascript. To make it easier for us, I'll use jQuery because it does a lot of work for you using real sweet syntax.
So, we need to find out how to calculate the offset. First we need to know the center of the blue element. Easy enough: blue.height / 2
. Next, we need to calculate how much the green div should go up when the top of the green div is aligned the actual center of the blue div. That's basically the half of the height of the green div, right? That gives us the next formula: (blue.height / 2) - (green.height / 2)
.
Alright, let's put that in javascript!
var center = $('div.blue').outerHeight(true) / 2; // this is the blue div
var offset = center - $('div.green').height() / 2;
And finally, setting the offset:
$('div.green').css({
'margin-top': margin
});
Cool theory, but I'm sure you want to see it in action. You can see the demo here.
Edit:
Oh yeah, I forgot to mention that jQuery is a cross-browser framework and supports very, very old browsers.. Read all about it here!
来源:https://stackoverflow.com/questions/9033277/vertical-align-div-in-relation-to-auto-height-div