在CSS网格布局中翻转表格行,使其独立于其他行

时间:2019-05-31 00:11:52

标签: html css css3 flexbox css-grid

我必须仅使用CSS重新排列这样的表。

<head>
<style>
table, th, td {border: 1px solid black; border-collapse: collapse; }
th, td {padding: 5px;}
th {text-align: left;}
</style>
</head>
<body>

<table>
    <tr>
        <th>H1</th>
	<th>H2</th>
	<th>H3</th>
        <th>H4</th>
	<th>H5</th>
	<th>H6</th>
	<th>H7</th>
	<th>H8</th>
	<th>H9</th>
	<th>H10</th>
    </tr>
    <tr>
	<td class="col-A1">A1</td>
        <td class="col-A2">A2</td>
	<td class="col-A3">A3</td>
	<td class="col-A4">A4</td>
	<td class="col-A5">A5</td>
	<td class="col-A6">A6</td>
	<td class="col-A7">A7</td>
	<td class="col-A8">A8</td>
	<td class="col-A9">A9</td>
	<td class="col-A10">A10</td>
    </tr>
    <tr>
	<td class="col-B1">B1</td>
	<td class="col-B2">B2</td>
	<td class="col-B3">B3</td>
	<td class="col-B4">B4</td>
        <td class="col-B5">B5</td>
	<td class="col-B6">B6</td>
	<td class="col-B7">B7</td>
	<td class="col-B8">B8</td>
	<td class="col-B9">B9</td>
	<td class="col-B10">B10</td>
    </tr>
</table>
</body>

如何获得这样的布局? 我最初的想法是使用CSS flexbox,但我不知道如何将行重新排列为这种布局,尤其是其中有两列的A2至A7部分。

因此,正如对原始帖子的评论所建议的那样,我会选择CSS网格布局。

Table final layout

1 个答案:

答案 0 :(得分:0)

对于,这是不可能的,即使您重新排列行,因为col-A9col-A10各自占据2.5列。而使用 flexbox ,您会发现跨行困难(例如col-A2),并且只有嵌套更多的容器才能解决。

但是使用CSS网格实际上很容易-您可以在此处使用20列布局。观看演示,内嵌说明:

.wrapper {
  display: grid; /* establish a grid container */
  grid-template-columns: repeat(20, 1fr); /* 20 columns */
  grid-auto-rows: 50px; /* row height for illustration */
}

.wrapper div {
  border: 1px solid;
  grid-column: span 2; /* span two columns */ 
  /* flexbox to center content*/
  display: flex;
  justify-content: center;
  align-items: center;
}

.wrapper .a {
  grid-column: span 10;  /* span ten columns */ 
}

.wrapper .a1 {
  grid-column: span 20; /* span all 20 columns */ 
}

.wrapper .a2 {
  grid-row: span 5; /* span five rows */ 
}

.wrapper .a9,.wrapper .a10{
  grid-column: span 5; /* span five columns */ 
}
<div class="wrapper">
  <div class="h">H1</div>
  <div class="h">H2</div>
  <div class="h">H3</div>
  <div class="h">H4</div>
  <div class="h">H5</div>
  <div class="h">H6</div>
  <div class="h">H7</div>
  <div class="h">H8</div>
  <div class="h">H9</div>
  <div class="h">H10</div>
  
  <div class="a a1">A1</div>
  <div class="a a2">A2</div>
  <div class="a a3">A3</div>
  <div class="a a4">A4</div>
  <div class="a a5">A5</div>
  <div class="a a6">A6</div>
  <div class="a a7">A7</div>
  <div class="a a8">A8</div>
  <div class="a a9">A9</div>
  <div class="a a10">A10</div>
  
  <div class="b">B1</div>
  <div class="b">B2</div>
  <div class="b">B3</div>
  <div class="b">B4</div>
  <div class="b">B5</div>
  <div class="b">B6</div>
  <div class="b">B7</div>
  <div class="b">B8</div>
  <div class="b">B9</div>
  <div class="b">B10</div>
  
</div>