How to keep content centered vertically and display any vertical overflow with a scrollbar?

Problem

I have a content area that should behave in the following way:

  • Content is centered vertically if there's no vertical overflow (currently achieved via display:table/-cell)
  • No scrollbar is displayed unless there is vertical overflow
  • the height of the containing div never changes

I've only been able to satisfy the first point - fiddle:

http://jsfiddle.net/PTSkR/119/

Here's my html:

<div class="row-fluid card-box">

    <div class="span4 side-study-box">
        <div class="side-box-content">
            <pre class="text-content-saved">TEST 
           TEST</pre>
            </div>
        </div>
</div>

Css:

.side-study-box {
    background-color: white;
    color: black;
    border: 1px solid #3D6AA2;
    text-align: center;
    height: 160px !important;
    max-height: 160px !important;
    display: table !important;
    margin: 0px !important;
    margin-left: -1px !important;
    position: relative;
    overflow-y: scroll !important;
}

    .side-study-box .side-box-content {
        width: calc(100%);
        height: 160px !important;
        float: right;
        display: table;
        overflow-y: scroll !important;
        background-color: white;
    }

    /*#region CONTENT AREAS */

    /*#region TEXT CONTENT */
    .side-study-box .text-content-saved {
        width: calc(100%+29px) !important;
        font-size: 24px;
        display: table-cell;
        vertical-align: middle;
        text-align: center;
        height: 160px !important;
        max-height: 160px !important;
        background-color: white;
        padding: 0px !important;
        margin: 0px !important;
        border: 0px !important;
        overflow-y: scroll !important;
    }
Problem courtesy of: SB2055

Solution

This can be accomplished using some basic CSS and a little jQuery.

Have a look at my fiddle. feel free to fill up the content to make it larger and see how ti responds.

http://jsfiddle.net/PTSkR/122/

HTML

<div id="holder">
    <div id="text">
        test<br/>
        test<br/>
        test<br/>
        test
    </div>    
</div>

CSS

#holder{
    height:200px; 
    width:100px;
    overflow:auto;
    border:1px dotted #999;
    position:relative;
}
#text{
    position:absolute;
    top:0;
}

JQuery

var holder = $('#holder');
var text = $('#text');

if (text.height()<holder.height()){
    var y=(holder.height()/2) - (text.height()/2);
    text.css({top:y+'px'});
}
Solution courtesy of: Dutchie432

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.