开发者

Vertical-centering and overflow Excel-style in CSS?

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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜