Vertical-align div in relation to auto height div

故事扮演 提交于 2019-12-11 04:45:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!