有没有办法在固定大小的div中执行可变大小的多行内容的垂直居中,并隐藏溢出?
目标是重现您在Excel单元格中可以看到的内容:当内容适合容器时,它应该是垂直居中的,当它更大时,应该隐藏溢出的部分(并且内容仍然垂直对齐) ,就像在邻居不为空的Excel单元格中一样。
我知道如何使用CSS垂直居中,我知道当内容不是垂直居中时如何隐藏溢出,但我不知道如何同时做两件事... Javascript是唯一的答案吗?
诀窍是CSS定位方法不适用于可变大小的内容(我的内容是动态文本),当你使用display:table-cell
时,它有效地禁用了CSS溢出控制(并且容器增长以适应内容)。
答案 0 :(得分:2)
这应该使所有细胞高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上尝试。