有没有一种方法可以在固定大小的div中对可变大小的多行内容执行垂直居中,并隐藏溢出?
目标是重现您在Excel单元格中可以看到的内容:当内容适合容器时,它应该垂直居中,当它较大时,溢出的部分应该隐藏(并且内容仍然垂直对齐),就像在相邻内容不为空的Excel单元格中一样。
我知道如何使用CSS垂直居中,我知道如何在内容不垂直居中时隐藏溢出,但我不知道如何同时做到这两个…Javascript是唯一的答案吗?
诀窍在于CSS定位方法不适用于可变大小的内容(我的内容是动态文本),当您使用display:table-cell时,它会有效地禁用CSS溢出控制(容器会增长以容纳内容)。
发布于 2010-05-11 20:56:25
这将使所有单元格的高度达到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上试用一下。
https://stackoverflow.com/questions/2810390
复制相似问题