【问题标题】:How to select first and last TD in a row?如何连续选择第一个和最后一个TD?
【发布时间】:2011-11-05 22:14:48
【问题描述】:

如何连续选择第一个和最后一个TD

tr > td[0],
tr > td[-1] {
/* styles */
}

【问题讨论】:

    标签: css css-selectors


    【解决方案1】:

    您可以使用 :first-child:last-child 伪选择器:

    tr td:first-child,
    tr td:last-child {
        /* styles */
    }
    

    这应该适用于所有主流浏览器,但 IE7 在动态添加元素时会出现一些问题(在 IE6 中不起作用)。

    【讨论】:

    • 如果你想选择第二个og第三个孩子怎么办?
    • tr > tdtr td有什么区别?
    • 下面的规则设置所有 P 元素的样式,它是 BODY 的子元素:body > P { line-height: 1.3 } 你可以看到:w3.org/TR/CSS2/selector.html#child-selectors(James 发布的同一页)
    • @clarkk - > 仅选择直接子级。没有它,将选择所有后代(例如孩子的孩子)。要选择第二个或第三个孩子,请查看 nth-child 伪选择器。
    • @BoltClock 我曾经看到您使用 + 解决了这个问题。类似tr td + td + .... +td 但如果我不知道我有多少 td 怎么办?
    【解决方案2】:

    你可以使用下面的sn-p:

      tr td:first-child {text-decoration: underline;}
      tr td:last-child {color: red;}
    

    使用以下伪类:

    :first-child 表示“如果该元素是其父元素的第一个子元素,则选择此元素”。

    :last-child 表示“如果它是其父元素的最后一个子元素,则选择此元素”。

    只有元素节点(HTML 标签)受到影响,这些伪类忽略文本节点。

    【讨论】:

      【解决方案3】:

      您可以使用 :first-child:last-child pseudo-selectors:

      tr td:first-child{
          color:red;
      }
      tr td:last-child {
          color:green
      }
      

      或者您可以使用其他方式,例如

      // To first child 
      tr td:nth-child(1){
          color:red;
      }
      
      // To last child 
      tr td:nth-last-child(1){
          color:green;
      }
      

      两种方式都可以正常工作

      【讨论】:

        【解决方案4】:

        如果该行在td 之前包含一些前导(或尾随)th 标记,则应使用:first-of-type:last-of-type 选择器。否则,如果第一个 td 不是该行的第一个元素,则不会选择它。

        这给出:

        td:first-of-type, td:last-of-type {
            /* styles */
        }
        

        【讨论】:

        • 你节省了我使用 last-child 的时间,但你的解决方案效果很好
        【解决方案5】:

        如果你使用 sass(scss) 你可以使用下面的 sn-p:

        tr > td{
           /* styles for all td*/
           &:first-child{
             /* styles for first */ 
           }
           &:last-child{
            /* styles for last*/
           }
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-28
          • 2014-04-30
          • 1970-01-01
          • 2021-08-17
          相关资源
          最近更新 更多