I have a div (#box
) on a page that is absolutely positioned a percentage from the top and bottom of the window. Naturally, this will resize when the window dimensions change,
Inside this div is content that can be anything from a few lines to several paragraphs. I would like this content to be vertically centred at all times, never exceeding #box
's height - with the main content overflowing when necessary.
HTML:
<div id="box">
<div id="content">
<h1>HEADING</h1>
<div id="left">
<p>
// Lorem ipsum etc...
</p>
</div>
</div>
</div>
CSS:
#box{
position:absolute;
top:15%; bottom:15%;
background:white;
left:50%;
}
#content{
position:absolute;
top:50%;
overflow:auto;
background:lightgrey;
}
jQuery(JavaScript):
function alignContent(){
// Position box
$box = $('#box');
$box.css({
'width' : $box.height() + 'px',
'margin-left' : '-' + $box.height()/2 + 'px'
});
// Position content
$content = $('#content');
console.log( $content.outerHeight() );
$content.css({
// Set maxheight smaller for aesthetic purposes
'max-height' : $box.height()-72 + 'px',
'margin-top' : '-' + ($content.outerHeight()/2) + 'px'
});
}
alignContent();
// Update when resized
$(window).resize(function(){
alignContent();
});
The approach is - I think - quite simple and works most of the time. The problem arises when the content is too tall for the #box
on page load - the content is incorrectly positioned (notice also that the console.log returns the wrong value). Resizing aligns everything correctly again.
What's making it align incorrectly on page load, when the content is taller than the container - and is it easily fixable?
Edit: Excuse my British inclination to spell it "centre"