【问题标题】:nth-child for every two table rows每两个表行的第 n 个孩子
【发布时间】:2012-09-04 17:06:42
【问题描述】:

我需要将表格的每两行设为灰色,如果可能,我更愿意使用 nth-child。

我已经搞砸了Chris Coyier's nth-child tester,但仍然无法得到它。

我需要以下公式:

1,2 - grey
3,4 - white
5,6 - grey
7,8 - white
9,10 - grey

等等。我不想在 html 中放置一个类,因为我确信这将是一些人的建议。如果有办法用 nth-child 解决这个问题,那就是我正在寻找的。​​p>

【问题讨论】:

  • 请发布您的代码,您尝试了什么?

标签: css css-selectors


【解决方案1】:

意识到你正在做 4 个一组,然后你可以看到你可以让每 4 个元素和每 4 个元素减一为白色,然后每 4 个元素减 2,或每 4 个元素减 3 为灰色。

因此,您将使用4n4n-1,然后使用4n-24n-3

div:nth-child(4n), div:nth-child(4n-1) {
    background: red;
}
div:nth-child(4n-2), div:nth-child(4n-3) {
    background: blue;
}

该代码对您的情况并不精确,我为jsFiddle proof-of-concept 编写了它。

NB 免责声明:请记住,nth-child 在 IE8 中不起作用。当然是典型问题。

【讨论】:

  • 这几乎就像您通过更改元素颜色来故意偏离他的情况:P
  • @BoltClock 可爱... 但是divs 的标记比tables 少,blue/red 更容易看到。 ;)
  • 我认为提问的目的是为了学习,而不是为了得到可以复制/粘贴的东西。如果您无法翻译使用与您的确切标记不同的标签的解决方案,那么您如何希望成长为前端设计师?
  • @samseabom 如果您希望您的代码可以投入生产,您可以随时聘请 Eric...
  • 这个 fiddle 是一个基于 Eric 原始示例的干净解决方案:jsfiddle.net/Wte4w/338
【解决方案2】:

这是我用来右对齐每个表的第一列的方法。

table td:nth-child(2n-1) {
    align: right;
    text-align: right;
}

【讨论】:

    【解决方案3】:

    @Eric 的回答是完全正确的 - 但如果你想轻松地将其扩展到 3、4、5 等组,并且你正在使用 Sass,这里是代码(如果你想要更多组,只需增加 @987654321 @):

    .table-with-grouped-rows {
    
        // generate styles for .groups-of-2, .groups-of-3, etc.
        $largestGroupSize: 6;
        @for $groupNumPerColor from 2 through $largestGroupSize{
    
            $totalGroupNum: $groupNumPerColor * 2;
    
            &.groups-of-#{$groupNumPerColor} {
    
                $start: $totalGroupNum - 1;
                $end: $groupNumPerColor;
                @for $primaryBgIndex from $start through $end {
                    $nthString: #{$totalGroupNum}n - #{$primaryBgIndex};
    
                    > tbody > tr:nth-of-type(#{$nthString}) > td {
                        background-color: $white;
                    }
                }
    
                $start: $groupNumPerColor - 1;
                $end: 0;
                @for $alternateBgIndex from $start through $end {
                    $nthString: #{$totalGroupNum}n - #{$alternateBgIndex};
                    > tbody > tr:nth-of-type(#{$nthString}) > td {
                        background-color: $light-gray;
                    }
                }
            }
        }
    }
    

    然后在您的标记中,在<table> 元素上,您只需添加类table-with-grouped-rowsgroups-of-{n}。例如,如果您想要一个包含 3 组的表格,您可以这样写:

    <table class="table-with-grouped-rows groups-of-3">
    

    轰隆隆。

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 2017-03-11
      • 2023-03-24
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多