代码之家  ›  专栏  ›  技术社区  ›  user448810

水平滚动和交替行背景色

  •  1
  • user448810  · 技术社区  · 6 年前

    <div style="overflow-x:auto;">
      <table>
        a bunch of tr/td ...
      </table>
    </div>
    

    table {
      font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
      border-collapse: collapse;
      width: 100%;
    }
    
    th,
    td {
      border: 1px solid #ddd;
      padding: 8px;
    }
    
    th {
      padding-top: 12px;
      padding-bottom: 12px;
      text-align: left;
      background-color: #00008B;
      color: white;
    }
    
    tr:nth-child(even) {
      background-color: #f2f2f2;
    }
    
    tr:hover {
      background-color: #ddd;
    }
    

    我看到两个错误:第一,水平滚动条没有出现。第二,偶数行与奇数行的背景色相同。这种行为在IE 11和Chrome 69之间是一致的。

    我做错了什么?我该怎么修?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Stickers    6 年前

    你需要解决几个问题:

    • table 元素,您可以尝试将其设置为 display:inline-table; min-width:100%; 如果需要,移除 width:100%; 让它成长。

    • tr:nth-child(even) {...} tr:nth-child(even) td {...} ; 对于列,使用 td:nth-child(even) {...}

    • 如果你也有 thead tfoot 你只想把颜色涂在 tbody ,用于添加 tbody tr:nth-child(even) 等。

    此外:

    你不必使用 <table>

    • 柔性箱: .container {display:inline-flex;}
    • .container {white-space:nowrap;} .item {display:inline-block; vertical-align:top; white-space:normal;}
    • CSS表格: .container {display:inline-table;} .item {display:table-cell;}

    当然,不管你选择哪种方式,都要保留包装纸 <div style="overflow-x:auto;"> 如果需要的话。