2

有没有办法在固定大小的 div 中执行可变大小的多行内容的垂直居中,并隐藏溢出?

目的是重现您在 Excel 单元格中看到的内容:当内容适合容器时,它应该垂直居中,当它更大时,应该隐藏溢出的部分(并且内容仍然垂直对齐),例如相邻不为空的 Excel 单元格。

我知道如何使用 CSS 垂直居中,我知道如何在内容未垂直居中时隐藏溢出,但我不知道如何同时做到这两个... Javascript 是唯一的答案吗?

诀窍是 CSS 定位方法不适用于可变大小的内容(我的内容是动态文本),并且当您使用 时display:table-cell,它会有效地禁用 CSS 溢出控制(并且容器会增长以适应内容)。

4

1 回答 1

3

这应该使所有单元格 65px 高,并使单元格的文本显示在中间。当文本太多时,文本会在下面消失。
我相信这是你想要的?

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>

你可以在JSFiddle上试试。

于 2010-05-11T12:56:24.507 回答