Skip to content Skip to sidebar Skip to footer

Vertical-align Div In Relation To Auto Height Div

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 th

Solution 1:

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 divvar 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!

Solution 2:

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:

<divid="container"><divid="container-inside">
        Some<br />
        content<br />
        is<br />
        in<br />
        here.<br /></div><divid="aligned">
        Aligned.
    </div></div>

Post a Comment for "Vertical-align Div In Relation To Auto Height Div"