簡體   English   中英

如何在 while 循環中為交替表行提供不同的背景 colors 和 CSS(不使用:nth-child() 選擇器)

[英]How to give alternating table rows different background colors in while loop and CSS (not using :nth-child() selector)

我正在嘗試將背景 colors 放入帶有 CSS 的 PHP while 循環表中。我無法找到如何編寫代碼來更改第一行和第一列(標題)colors 以及從左上角斜下方更改顏色.

我知道表 header 可以通過在 CSS 中使用<th>來更改,但我不確定如何在 PHP 中使用<th> 。我做了一些研究,獲得此乘法表的唯一解決方案如下。

注意 nth-child() 選擇器是不允許的。

這是我的代碼的樣子:

    <!DOCTYPE html>
    <html>
    <head>
        <title>table</title>
    </head>
    <body>
    
        <table border = "1">
            <?php
     
    $x = 1; //rows
    echo "<table border = '1'>\n";
     
    while ( $x <= 12 ) {
        echo "\t<tr>\n";
     
        $y = 1;//columns
        while ( $y <= 12 ) {
            echo "\t\t<td>$x x $y = " . $x * $y . "</td>\n";//the result of the multiplication
            $y++;
        }
     
        echo "\t</tr>\n";
        $x++;
    }
     
    echo "</table>";
     
    ?>
        </tr>
                </div>
            </table>
    </body>

CSS 代碼如下。

    <style>
    table {
        width: 100%;
        height: 400px;
         font-family: arial, sans-serif;
         border-collapse: collapse;
    }
     tr{
        background-color: #FF8A65;
    }
    
    </style>
    </html>

它應該是這樣的:

桌子

你的意思是這樣的

<!DOCTYPE html>
<html>
<head>
    <title>table</title>
    <style>
    table {
        width: 100%;
        height: 400px;
         font-family: arial, sans-serif;
         border-collapse: collapse;
    }
     tr{
        background-color: #82BFBF;
    }
    
    </style>
</head>
<body>
    
    <table border = "1">
<?php
     
    $x = 1; //rows
    echo "<table border = '1'>\n";
     
    while ( $x <= 12 ) {
        if ( $x == 1)
            echo "\t<tr style='background-color:green'>\n";
     
        $y = 1;
        while ( $y <= 12 ) {
            $bgc = '';
            if ( ($y == 1 || $x == 1) && $y != $x) {
                $bgc = "style='background-color:green'";
            } elseif ( $y == $x ) {
                $bgc = "style='background-color:red'";
            } elseif ($y > 1 && $x % 2){
                $bgc = "style='background-color:#FF8A65'";
            }
            echo "\t\t<td $bgc>$x x $y = " . $x * $y . "</td>\n";
            $y++;
        }
     
        echo "\t</tr>\n";
        $x++;
    }
     
    echo "</table>";
     
?>
    </tr>
            </div>
        </table>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM