【问题标题】:Apply style in a table to specific columns within the th and td将表格中的样式应用于 th 和 td 中的特定列
【发布时间】:2018-12-25 03:05:21
【问题描述】:

我有一个表格,我希望能够将 CSS 中的特定样式分配给表格中的某些列:-

<table border="1">

<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
<th>Header 5</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
<td>row 1, cell 3</td>
<td>row 1, cell 4</td>
<td>row 1, cell 5</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
<td>row 2, cell 3</td>
<td>row 2, cell 4</td>
<td>row 2, cell 5</td>
</tr>

</table>​

我希望能够只给前 2 个样式 text-align:left; 和其余的 th = text-align:center;

【问题讨论】:

    标签: html css html-table


    【解决方案1】:

    标准和直接解决方案:

    th {
       text-align:center;       
    }
    tr th:nth-child(1), tr th:nth-child(2) {
       text-align:left;   
    }​
    

    这种表示法的优点是很容易将其更改为例如应用于第四个和第六个th 而不是前两个。

    请注意,这假设为the availability of CSS3 in the browser

    如果你想兼容 IE8,你可以在 javascript 中轻松做到:

    var ths = document.getElementsByTagName('th'); // replace document by your table if necessary    
    for (var i=2; i<ths.length; i++) ths[i].style.textAlign="center";
    

    或使用 jQuery :

    ​$('th').each(function(){
        if ($(this).index()>=2) $(this).css('text-align', 'center');
    }​​​​​​​​​​​​​​​​​​​​​​​​​​​​​);​
    

    【讨论】:

      【解决方案2】:

      CSS3方式

      th {
      text-align:center;
      }
      th:nth-child(0), th:nth-child(1) { text-align:left; }​
      

      CSS2 方式

      th{
      text-align:center;
      }
      th:first-child, th:first-child + th{
      text-align:left;
      }
      

      【讨论】:

        【解决方案3】:

        这样做

            th:first-child, th:first-child + th{
                text-align:left;
                }
        th + th + th{
                text-align:center;
                }
        

        现场演示http://tinkerbin.com/B5Zi88Pp

        【讨论】:

          猜你喜欢
          • 2014-06-04
          • 1970-01-01
          • 2019-01-06
          • 2013-02-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-04
          相关资源
          最近更新 更多