繁体   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