Note that there are some explanatory texts on larger screens.

plurals
  1. POVertically centering a div with unknown height
    text
    copied!<p>I have a div (<code>#box</code>) 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,</p> <p>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 <code>#box</code>'s height - with the main content overflowing when necessary.</p> <p>HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="box"&gt; &lt;div id="content"&gt; &lt;h1&gt;HEADING&lt;/h1&gt; &lt;div id="left"&gt; &lt;p&gt; // Lorem ipsum etc... &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>#box{ position:absolute; top:15%; bottom:15%; background:white; left:50%; } #content{ position:absolute; top:50%; overflow:auto; background:lightgrey; } </code></pre> <p>jQuery(JavaScript):</p> <pre class="lang-js prettyprint-override"><code>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(); }); </code></pre> <p><a href="http://jsfiddle.net/verism/aSue8/" rel="nofollow">See it working.</a></p> <p>The approach is - I think - quite simple and works most of the time. The problem arises when the content is too tall for the <code>#box</code> on page load - the content is incorrectly positioned (notice also that the console.log returns the wrong value). Resizing aligns everything correctly again.</p> <p>What's making it align incorrectly on page load, when the content is taller than the container - and is it easily fixable?</p> <p><strong>Edit</strong>: Excuse my British inclination to spell it "centre"</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload