[英]Seperate th and td in table with css
我试图使一个表响应移动设备,并且使td和th显示值块变好了。 唯一的问题是,标题都彼此堆叠在一个组中,而数据全部堆叠在它们自己的组中。 我要使其标题为第一,然后是该特定行的数据,然后是下一个标题和数据,依此类推。 我想仅使用CSS完成此操作。 以下是我刚刚复制并粘贴的代码。 我真的不想用PHP弄乱任何东西,因为不完全了解它。 他就是我要显示的内容:在数据下方放置一个数据,然后在td之后显示下一个及其td,依此类推。 我将此问题的摘要中的代码包含在jsfidle中,因为该选项卡在我的计算机上不起作用。
从你的陈述
我制作了td和th显示值块,因此使它更好一点。 唯一的问题是,标题都彼此堆叠在一个组中,而数据全部堆叠在它们自己的组中。
在th
和td
添加display:block
将使您的内容堆积在一个单元格中,如下所示:
header1
content1
content2
content3
header2
content1
content2
content3
要么
header1
header2
content1
content2
content3
content1
content2
content3
我要使其标题为第一,然后是该特定行的数据,然后是下一个标题和数据,依此类推。
我猜您希望您的表是这样的:
header1 | content1 | content2 | content 3
header2 | content1 | content2 | content 3
header3 | content1 | content2 | content 3
这是JSFiddle中的一个示例
更新
从您的jsfiddle中,您真的在表中没有<tr>
吗? 因为<tr>
是一个,它将把您的<th>
与<td>
分开。 我从您的jsfiddle中添加了<tr>
,它看起来像这样:
那是你想要的桌子吗? 这是Jsfiddle 。
首先,您可以将表标题单元格放在thead
元素中,而其他表单元格放在tbody
。 之后,您可以在tbody
的tr
所有第一个td
之前复制并放置thead
的th
。 抱歉,要弄清楚它并不容易。 这是一个例子
<table>
<thead>
<tr>
<th>header1</th>
<th>header2</th>
</tr>
</thead>
<tbody>
<tr>
<th>header1</th><!-- as in the thead -->
<td>Content1</td>
<td>Content2</td>
</tr>
<tr>
<th>header2</th><!-- as in the thead -->
<td>Content1</td>
<td>Content2</td>
</tr>
</tbody>
</table>
在CSS中,当您处于移动状态时,您应该隐藏thead
并仅显示tbody th
。 在平板电脑/台式机中,您可以进行相反的操作。
<style>
/* Mobile first */
table,
thead,
tbody,
tr,
th,
td {
display:block;
}
th,
td {
text-align:left;
}
th {
background:#f00;
}
td {
background:#0099ff;
}
thead {
display:none;
}
tr {
margin-bottom:16px;
}
/* When you going up 768px */
@media screen and (min-width:768px) {
table {
border:2px solid #000;
display:table;
width:100%;
}
tr {
display:table-row;
}
td,
th {
display:table-cell;
}
thead,
tbody {
display:table-header-group;
}
tbody th {
display:none;
}
}
</style>
小提琴: https : //jsfiddle.net/uc8q0u96/ 。
在tbody
的tr
所有第一个td
上创建数据属性并将相应的标头单元格的内容放进去可能会更干净:
<table>
<thead>
<tr>
<th>header1</th>
<th>header2</th>
</tr>
</thead>
<tbody>
<tr>
<td data-header="header1">Content1</td>
<td>Content2</td>
</tr>
<tr>
<td data-header="header2">Content1</td>
<td>Content2</td>
</tr>
</tbody>
</table>
并使用::before
伪元素来获取CSS中data-header
属性的内容:
/* Mobile first */
table,
thead,
tbody,
tr,
th,
td {
display:block;
}
td[data-header]:before {
background:yellowgreen;
content:attr(data-header);
display:block;
}
th,
td {
text-align:left;
}
th {
background:#f00;
}
td {
background:#0099ff;
}
thead {
display:none;
}
tr {
margin-bottom:16px;
}
/* When you going up 768px */
@media screen and (min-width:768px) {
table {
border:2px solid #000;
display:table;
width:100%;
}
tr {
display:table-row;
}
td,
th {
display:table-cell;
}
thead,
tbody {
display:table-header-group;
}
td[data-header]:before {
display:none;
}
}
小提琴https://jsfiddle.net/o9mtfsdL/3 。
Voilà。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.