Excel style vertical centering and overflow in CSS?
Is there a way to vertically center multiline variable sized content in a fixed size div with hidden overflow?
The goal is to reproduce what you can see in the 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 is still vertically aligned). as in an Excel cell whose neighbors are not empty.
I know how to vertically center using CSS, I know how to hide the overflow when the content is not vertically centered, but I don't know 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 do display:table-cell
, it effectively disables CSS overflow control (and the container grows to accommodate the content).
a source to share
This should make all cells 65px high and make the cell text in the middle. When there is too much text, the text disappears below.
I believe 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 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 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 the JSFiddle .
a source to share