Question

I have a number of "rows" which I want to have grouped together and centered in their container, somethign like this:

Centered rows

However, the number of rows is variable, and if there are enough rows to overflow a set height, I want it to scroll.

The best way I have found to get it to center the rows properly is to use the following css on the container:

.container {
    display: table-cell;
    vertical-align: middle;
}

However, since the container doesn't have display:block, setting overflow:auto doesn't work. Putting a scrolling div inside the table cell doesn't work either, because the scrolling div needs to have a set height, and that destroys the vertical centering.

Was it helpful?

Solution

After much experimentation, I have finally arrived at the following solution:

html:

<div class="scroll">
    <div class="table">
        <div class="container">
            <div class="row" ></div>
            <div class="row" ></div>
            ...
        </div>
    </div>
</div>

css:

.scroll {
    overflow-y: auto;
    height: 80px;
}
.table {
    display: table;
    height: 100%;
    width: 100%;
}

.container {
    display: table-cell;
    vertical-align: middle;
}

See http://jsfiddle.net/ZCdPG/ for a full implementation.

Although it works, it is unfortunate that it requires three levels of nesting for a single container. Web components would somewhat alleviate this, but the real problem is that there is no real support for vertical centering in CSS, and a common use case can only be achieved with hacks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top