css 垂直渲染表行

kwvwclae  于 2023-10-21  发布在  其他
关注(0)|答案(3)|浏览(115)

是否可以垂直呈现表格行:如果我有这样的代码,

<table>
   <tr> 
      <td>row1 - cell1</td>
      <td>row1 - cell2</td>
      <td>row1 - cell3</td>
   </tr>
   <tr> 
      <td>row2 - cell1</td>
      <td>row2 - cell2</td>
      <td>row2 - cell3</td>
   </tr>
   <tr> 
      <td>row3 - cell1</td>
      <td>row3 - cell2</td>
      <td>row3 - cell3</td>
   </tr>
</table>

这将呈现一个这样的表:

row1-cell1 | row1-cell2 | row1-cell3
------------------------------------
row2-cell1 | row2-cell2 | row2-cell3
------------------------------------
row3-cell1 | row3-cell2 | row3-cell3

我想要的是这样展示它

row1-cell1 | row2-cell1 | row3-cell1
------------------------------------
row1-cell2 | row2-cell2 | row3-cell2
------------------------------------
row1-cell3 | row2-cell3 | row3-cell3
oxcyiej7

oxcyiej71#

您可以在表行上使用display: inline-flex;flex-direction: column;来实现这一点。

tr {
  display: inline-flex;
  flex-direction: column;
}

td {
  padding: 5px;
}
<table>
  <tr>
    <td>row1 - cell1</td>
    <td>row1 - cell2</td>
    <td>row1 - cell3</td>
  </tr>
  <tr>
    <td>row2 - cell1</td>
    <td>row2 - cell2</td>
    <td>row2 - cell3</td>
  </tr>
  <tr>
    <td>row3 - cell1</td>
    <td>row3 - cell2</td>
    <td>row3 - cell3</td>
  </tr>
</table>
qc6wkl3g

qc6wkl3g2#

假设你有一个对象数组:

function toTable(){
        var html = "<table>";
        for(var i=0; i < array.length; i++){
            var row = Object.keys(array[i]);
            html += "<tr>";
             for(var x=0; x < row.length; x++){
                  html += "<td>" + row[x] + "</td>";
             }
            html += "<tr>";
        }
        html += "</table>";
    }
6tdlim6h

6tdlim6h3#

<table class="vertical-table">
   <tr> 
      <td>row1 - cell1</td>
      <td>row1 - cell2</td>
      <td>row1 - cell3</td>
   </tr>
   <tr> 
      <td>row2 - cell1</td>
      <td>row2 - cell2</td>
      <td>row2 - cell3</td>
   </tr>
   <tr> 
      <td>row3 - cell1</td>
      <td>row3 - cell2</td>
      <td>row3 - cell3</td>
   </tr>
</table>

CSS样式

.vertical-table {
   display: table;
}

.vertical-table tr {
   display: inline-grid;
}

.vertical-table td {
   display: table-cell;
   border: 1px solid black;
}

输出

相关问题