Reputation: 129
I'm looking for a way to fit table content to table size. For example, I have table with width and height =100, and 5 col and 5 row, if row or col change to 20 only content re-size to fit into old table size. I wrote some code, but it resize table if row or col change!
<style>
.tbl {
max-width: 100px;
max-height: 100px;
height: 100px;
width: 100px;
border: 1px solid #333;
}
.blck {
border: 1px solid #0F3;
background:#F00;
}
.wht {
border: 1px solid #0F3;
background:#069;
}
</style>
<?php
$w = 15;
$h = 15;
$max = 100;
if ($w>=$h) {
$cell = ($max/$w);
} else {
$cell = ($max/$h);
}
$clr = 0;
$tbl .= '<table width="'.$max.'px" align="center" border="0" height="'.$max.'px" class="tbl">';
for ($r=1;$r<=$h;$r++){
$tbl .= '<tr>';
for($c=1;$c<=$w;$c++){
if($clr == '0'){
$tbl .= '<td width="'.$cell.'%" height="'.$cell.'%" class="blck"></td>';
$clr = 1;
} else {
$tbl .= '<td width="'.$cell.'%" height="'.$cell.'%" class="wht"></td>';
$clr = 0;
}
}
$tbl .= '</tr>';
}
$tbl .= '</table>';
echo $tbl;
?>
Upvotes: 0
Views: 2705
Reputation: 2233
be careful when you add borders to the table cells, because it will add 2px to the current width/height. use floor() when you divide the table width by cols/rows count, because width and height attributes doesn't accept fractions.
And it seems that height attribute is not accurate (no idea why).
Also you have to consider text size. for example i put:
font-size: 1px;
line-height: 1px;
Check this out:
<?php
$w = 30;
$h = 30;
$max = 100;
if ($w>=$h) {
$cell = floor($max/$w);
} else {
$cell = floor($max/$h);
}
?>
<style type="text/css">
.tbl {
display: table;
height: <?php echo ($cell*$h); ?>px;
width: <?php echo ($cell*$w); ?>px;
font-size: 1px;
line-height: 1px;
}
.blck {
background-color: #F00;
}
.wht {
background-color: #069;
}
.tbl .tr {
display: table-row;
}
.tbl .td {
width: <?php echo $cell;?>px;
height: <?php echo $cell;?>px;
display: table-cell;
}
</style>
<?php
$fcell = $clr = 0;
$tbl .= '<div class="tbl">';
for ($r=1;$r<=$h;$r++){
$tbl .= '<div class="tr">';
for($c=1;$c<=$w;$c++){
if($clr == '0'){
$tbl .= '<div class="td blck"> </div>';
$clr = 1;
} else {
$tbl .= '<div class="td wht"> </div>';
$clr = 0;
}
}
$tbl .= '</div>';
if ($fcell == 0){
$fcell = $clr = 1;
} else {
$fcell = $clr = 0;
}
}
$tbl .= '</div>';
echo $tbl;
?>
Upvotes: 2
Reputation: 10712
if i understood you correctly you want to manage the size of the table in your own logic. if any content in a cell of the table should overflow for some reason you don't want it to grow. you want it to stay static in that case try adding this attribute
table
{
table-layout:fixed;
}
Upvotes: 0