【问题标题】:How to select the first TD elements in a Row如何选择一行中的第一个 TD 元素
【发布时间】:2021-03-16 06:17:59
【问题描述】:

我有一些行的表。 我想创建一个 CSS,允许我以递归方式更改 TR 行中第一个 TD 元素的颜色,仅适用于具有 mytable 类的表。

你能给我一个 CSS 样本吗?

<table class="mytable">
    <tr>
        <td>Event Title:</td><!--Change color here-->
        <td>{EventTitle}</td>
    </tr>
    <tr>
        <td>Start date:</td><!--Change color here-->
        <td>{DateTimeStart}</td>
    </tr>
    <tr>
        <td>End date:</td><!--Change color here-->
        <td>{DateTimeEnd}</td>
    </tr>
</table>

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    为此,您可以使用 :first-child 属性。像这样写:

    .mytable td:first-child{
     color:red;
    }
    

    【讨论】:

    • 所有浏览器都支持吗?
    • 我只需要申请class="mytable",怎么办?谢谢
    • 这样写 .mytable td:first-child{}
    • .myTable td:first-child{color:red;}
    • @sandeep:“直到”的意思是“从某个旧版本到这个新版本,但不是任何新版本”。你的意思是说“它 IE7开始工作。”
    【解决方案2】:

    使用 CSS “first-child”元素:http://www.w3schools.com/cssref/sel_firstchild.asp

    所以可以这样做:

    .mytable td:first-child {
       something here
    }
    

    【讨论】:

      【解决方案3】:

      正如@sandeep 所写,您可以使用 first-child 来实现目标。如果可能的话,更好的方法是将类名添加到您的第一个 td.如果这应该是标题,您可能还想使用 th 而不是 td

      【讨论】:

      • 那会是更好的方法吗?让代码更脏是更好的方法?
      【解决方案4】:

      Sandeep 的想法是正确的,但您似乎要求的样式规则更具体一些。试试这个:

      table.mytable td:first-child {}
      

      【讨论】:

        【解决方案5】:

        :first-child 在 IE 中不起作用,一种实用的方法是更改​​这些 td,您要为 th 应用背景,然后设置它们的样式

        【讨论】:

          【解决方案6】:

          你可以试试这个:

          HTML

          <table class="mytable">
                          <tr>
                                  <td>Event Title:</td><!--Change color here-->
                                  <td>{EventTitle}</td>
                          </tr>
                          <tr>
                                  <td>Start date:</td><!--Change color here-->
                                  <td>{DateTimeStart}</td>
                          </tr>
                          <tr>
                                  <td>End date:</td><!--Change color here-->
                                  <td>{DateTimeEnd}</td>
                          </tr>
                  </table>
          

          CSS

          .mytable tr td:first-child{
           color:red;
          }
          

          http://jsfiddle.net/hrBAn/1/

          【讨论】:

            猜你喜欢
            • 2023-03-25
            • 1970-01-01
            • 1970-01-01
            • 2012-03-15
            • 1970-01-01
            • 2018-11-15
            • 2023-03-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多