Is there a way to set the text alignment of entire column in a table?

前端 未结 6 1320
南笙
南笙 2020-12-29 01:11

Is there a simple way to set the text alignment of all cells in the second column to right?

Or is the only way is to set the alignment for each cell in

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 01:43

    Bit late to the party, but I just had this issue myself so thought I'd share a resolution. It's worth noting that this answer is only applicable if you are using LESS.

    Instead of having to manually add the class or style to each cell you can use loops in LESS to create a range of classes that you can apply to your tables:

    // Loop for @i until @i = @n
    // Much like - for($i=0; $i<=$n; $i++)
    //
    .table-cols(@n, @i: 1) when (@i =< @n)
    {
        .table-center-col-@{i}
        {
            tr > td:nth-child(@{i})
            {
                text-align: center;
            }
        }
    
        .table-right-col-@{i}
        {
            tr > td:nth-child(@{i})
            {
                text-align: right;
            }
        }
    
        // Continue the iteration
        .table-cols(@n, (@i + 1));
    }
    
    .table-cols(16);
    

    This will produce a load of classes such as .table-center-col-1 all the way up to .table-center-col-16 (in this example) and they will make center the text of the applicable column. It will also do the same for right-aligned text, with .table-right-col-n.

    You can adjust the number supplied (from 16) to anything to ensure that it covers you for the max amount of columns you may have in a table. For variable column numbers this won't be much help to you.

    Then all you have to do is apply it to the table:

    Column 1 Column 2 Column 3 Column 4 Column 5
    x x x x x

    All of the cells in the 4th column will now have centered text.

提交回复
热议问题