Adjust fontsize in fixed-height/width table cells in Javascript/jQuery
I want to make a a printable schedule as table with fixed height/width cells. Cells contains names and I don't want that the names do li开发者_运维技巧ne breaks.
Is there a way to dynamically adjust the font-size so that there will be no linebreaks or hiding text?
Maybe someone knows a good plugin or snippet for that issue?
Try wrapping the contents of each cell with another element (table cells don't support overflow :hidden
) with white-space: nowrap
and overflow: hidden
and reducing the font-size
of that element until it's contents fit into it.
Example code:
HTML:
<table>
<tbody>
<tr>
<td><span>cell</span></td>
<td><span>another cell</span></td>
<td><span>yet another cell</span></td>
</tr>
</tbody>
</table>
CSS:
td span {
display: block;
white-space: nowrap;
width: 100px;
overflow: hidden;
font-size: 100%;
}
JS:
$(function() {
$('td span').each(function() {
var fontSize = 100;
while (this.scrollWidth > $(this).width() && fontSize > 0) {
// adjust the font-size 5% at a time
fontSize -= 5;
$(this).css('font-size', fontSize + '%');
}
});
});
Working version of the example (JSBin).
精彩评论