首页 > 解决方案 > 使用 CSS 将表格行显示为列

问题描述

我希望标签和值使用表格根据最长的标签大小正确对齐。对于大屏幕尺寸,我想将 2 个表格行的集合显示为列(如图 B 所示)。是否有唯一的 CSS 方法来实现这种响应式显示更改?

沙盒

<div class="table">
 <div class="row">
   <div class="cell">label 1</div>
   <div class="cell">value 1</div>
</div>
<div class="row">
  <div class="cell"> looooooooooong label 2</div>
  <div class="cell">value 2</div>
</div>
<div class="row">
  <div class="cell">label 3</div>
  <div class="cell">value 3</div>
</div>  
<div class="row">
  <div class="cell">label 4</div>
  <div class="cell">value 4</div>
</div>  
</div>

表的响应状态:

标签: htmlcss

解决方案


这是对@Fakt309 开始的解决方案的改进。我使用flex-order(订单)重新排列大屏幕的项目。

@media only screen 
  and (min-width: 801px) {
    .row:nth-of-type(1) {
      order: 1;
    }
      
    .row:nth-of-type(2) {
      order: 3;
    }
      
    .row:nth-of-type(3) {
      order: 2;
    }
      
    .row:nth-of-type(4) {
      order: 4;
    }
}

我还添加flex-direction: column;了小屏幕以使这些项目在彼此下方对齐。

.table {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  flex-wrap: wrap;
}
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  width: 40%;
}
.cell {
  padding: 20px;
  width: 40%;
  word-break: break-all;
}

@media only screen 
  and (max-width: 800px) {
    .table {
      flex-direction: column;
    }
    
    .row {
      width: 90%;
    }
}

@media only screen 
  and (min-width: 801px) {
    .row:nth-of-type(1) {
      order: 1;
    }
  
    .row:nth-of-type(2) {
      order: 3;
    }
  
    .row:nth-of-type(3) {
      order: 2;
    }
  
    .row:nth-of-type(4) {
      order: 4;
    }
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

<div class="table">
 <div class="row">
   <div class="cell">label 1</div>
   <div class="cell">value 1</div>
</div>
<div class="row">
  <div class="cell"> looooooooooong label 2</div>
  <div class="cell">value 2</div>
</div>
<div class="row">
  <div class="cell">label 3</div>
  <div class="cell">value 3</div>
</div>
<div class="row">
  <div class="cell">label 4</div>
  <div class="cell">value 4</div>
</div>
</div>


推荐阅读