views:

232

answers:

1

Is there a way to perform a vertical centering of a variable-sized multi-line content within a fixed-size div, with hidden overflow?

The aim would be to reproduce what you can see in Excel cells: when the content fits the container, it should be vertically centered, when it is larger, the parts that overflow should be hidden (and the content still vertically aligned), like in an Excel cell whose neighbours aren't empty.

I know how to vertically center using CSS, I know how to hide overflow when the content isn't vertically centered, but I've no idea how to do both at the same time... Is Javascript the only answer?

The trick is that CSS positioning approaches don't work with variable-sized content (my content is dynamic text), and when you use display:table-cell, it effectively disables CSS overflow control (and the container grows to accomodate the content).

+1  A: 

This should make all the cells 65px high, and make the cells' text show up in the middle. When it's too much text, the text disappears bellow.
I believe it's what you want?

CSS:

.row {
  border: solid 1px blue;
  display: block;
  height: 65px; /* arbitrary value */
  overflow: hidden;
  line-height: 65px; /* same as height */
}

.cell {
  border: solid 1px #CCCCCC;
  display: inline-block;
  vertical-align: middle;
  height: 100%;
}

.cellContents {
  display: inline-block;
  max-height: 100%;/*would 100%; work?*/
  width: 100px; /* arbitrary value */
  overflow: hidden;
  border: solid 1px red; /* just to see that it's centered */
  line-height: 100%; /* so it does not inherit the huge line-height, and we get more than one line of text per cell */
}

HTML:

<div class="table">
    <div class="row">
        <span class="cell"><span class="cellContents">cell 1 1</span></span>
        <span class="cell"><span class="cellContents">cell 1 2</span></span>
        <span class="cell"><span class="cellContents">cell 1 3</span></span>
    </div>

    <div class="row">
        <span class="cell"><span class="cellContents">cell 2 1</span></span>
        <span class="cell"><span class="cellContents">This should make all the cells 65px high, and make the cells' text show up in the middle. When it's too much text, the text disappears bellow.</span></span>
        <span class="cell"><span class="cellContents">cell 2 3</span></span>
        <span class="cell"><span class="cellContents">cell 2 4</span></span>
    </div>
</div>

You can try it on JSFiddle.

ANeves
Tried it on JSFiddle, but the content doesn't seem to be vertically centered, content is top-left aligned... (this is on Firefox)btw, didn't knew about jsfiddle, nice :)
Eric Grange
Indeed, it's not. I'll try playing around with it a bit.
ANeves
I think it's fixed, take a look. :)
ANeves
Nice it works! so the trick is to specify both height and line-height in the container, and use line-height 100% in the content, wicked!
Eric Grange
:) It's great fun juggling CSS.
ANeves