2012-08-14 33 views
0

我在尋找一種方法來適應表內容,以表大小 例如我有寬度和高度= 100,和5欄和第5行的表中,如果行或COL變化至20只有內容重新調整大小以適應舊桌子大小。 我寫了一些代碼: 但它reszie表如果行或列更改!如何配合內容表的大小

<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; 

?> 
+0

$ w是行號,$ h是山坳 – OceanOne 2012-08-14 19:51:36

+0

的號碼,您可以使用非固定寬度,讓瀏覽器的大小根據需要? – 2012-08-14 19:52:00

+0

我正在使用填字遊戲,我想顯示一個迷你的謎題審查,並希望它在固定的大小,而不是更多! – OceanOne 2012-08-14 19:55:11

回答

1

的時候要小心添加邊框的表格單元格,因爲它會增加2px的當前的寬度/高度。 由於寬度和高度屬性不接受分數,所以在將表格寬度除以cols/rows計數時使用floor()。

它似乎height屬性是不準確的(不知道爲什麼)。

你也必須考慮文字大小。比如我放:

font-size: 1px; 
line-height: 1px; 

檢查了這一點:

<?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">&nbsp;</div>'; 
       $clr = 1; 
      } else { 
       $tbl .= '<div class="td wht">&nbsp;</div>'; 
       $clr = 0; 
      } 
     } 
    $tbl .= '</div>'; 

    if ($fcell == 0){ 
     $fcell = $clr = 1; 
    } else { 
     $fcell = $clr = 0; 
    } 
} 

$tbl .= '</div>'; 

echo $tbl; 

?> 
+0

謝謝,它真的有幫助。 – OceanOne 2012-08-14 22:35:36

0

如果我正確地理解了你,你想按自己的邏輯管理表的大小。 如果表格單元格中的任何內容由於某種原因而溢出,則不希望它增長。你想讓它留靜態在這種情況下嘗試添加該屬性

table 
{ 
    table-layout:fixed; 
} 
+0

Mortalus:它固定表的寬度,但不是內容,並且內容從表中溢出,代碼對於行或列的工作更少15但不更多 – OceanOne 2012-08-14 20:10:35

+0

實際上我忘了說:代碼工作少於15行或列,但我想要爲30列或行工作。 – OceanOne 2012-08-14 20:16:09

+0

單元格內容溢出?你的意思是卷軸?...... – Mortalus 2012-08-15 02:35:26