2010-05-11 21 views
2

是否有一個固定大小的格內執行可變大小的多行的內容的垂直定心,具有隱藏溢出的方法嗎?在CSS中垂直居中和溢出Excel樣式?

其目的是重現您在Excel單元格中可以看到的內容:當內容適合容器時,應該垂直居中,當它較大時,應該隱藏溢出的部分(並且內容仍然垂直對齊),就像在一個Excel單元格中,它的鄰居不是空的。

我知道如何使用CSS垂直居中,我知道如何隱藏溢出時,內容不垂直居中,但我不知道如何在同一時間做兩... JavaScript是唯一的答案?

訣竅是,CSS定位方法不適用於可變大小的內容(我的內容是動態文本),並且當您使用display:table-cell時,它有效地禁用了CSS溢出控制(並且容器增長以適應內容) 。

+0

我有一個溶液(但醜陋):使用表用表格的佈局設置爲固定爲容器,以此方式該表內的TD元素將不會生長,並且將兌現既垂直取向和溢出。 這是一個有點沉重,但非CSSish ... – 2010-05-11 12:37:35

回答

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

+0

尼斯它的作品!所以訣竅是在容器中指定高度和行高,並且在內容中使用行高100%! – 2010-05-12 07:37:26

+0

:)玩雜耍CSS非常有趣。 – ANeves 2010-05-13 09:34:13