Разбить строку таблицы на несколько строк (отзывчивый макет)
У меня есть веб-страница, в которой перечислены элементы. Шаблон по умолчанию использует для этого таблицу, которую я считаю очень подходящей. Однако в этой таблице есть один столбец, который содержит гораздо больше текста, чем другие:
![enter image description here]()
Пока это работает на большом экране, очень мало надо читать на маленьком экране:
![enter image description here]()
Чтобы лучше использовать доступное пространство, я могу думать только о макете фальшивых таблиц с помощью div. Я сделал прототип, используя макет сетки начальной загрузки, который выглядит как строка таблицы на больших экранах, но имеет разный макет на маленьких и дополнительных маленьких экранах:
![enter image description here]()
Хотя это улучшает читаемость текста с использованием полной ширины, я больше не могу использовать утилит, которые у меня есть для таблиц, и это затрудняет работу пользователя. Например, я использую приятный script, который позволяет сортировать на клиенте. Но это работает только на реальных таблицах. (Кроме того, существуют небольшие несоответствия и визуальные различия между реальными таблицами и поддельными таблицами)
Есть ли способ переформатировать строку таблицы в многострочный контейнер, аналогичный таковой в последнем изображении?
FYI: Я использую jquery 2.1.1, Bootstrap 3.2.0.1 в качестве GUI Framework и asp.net MVC на сервере.
Bootply находится здесь: http://www.bootply.com/pRehwTai4G
Изменить: в случае, если это не получилось достаточно ясно: я хочу хранить теги <tr>
и <td>
, но стилю их аналогично div. Я не хочу заменять таблицу на div.
Ответы
Ответ 1
Вы можете взглянуть на Реагирующие таблицы данных. Если это не соответствует вашим потребностям, вы можете использовать JavaScript для повторного создания табличных представлений в виде div. Это было бы проще всего, если бы вы могли получать данные таблицы как JSON, которые были бы преобразованы в таблицы или div - в зависимости от разрешения. Если вы не можете использовать его как JSON, вы всегда можете использовать jQuery html() или text(), чтобы получать данные из ячеек таблицы и повторно рисовать в div.
Ответ 2
Если вы удалите тег thead
из своей таблицы и привяжите th
внутри tbody
, вы можете использовать следующий jquery с кодом css для получения гибких таблиц:
HTML
<table class="table table-striped">
<tbody>
<tr>
<th class="col-sm-1">Col 1
</th>
<th class="col-sm-2">Col 2
</th>
<th class="col-sm-6">Col 3
</th>
<th class="col-sm-1">Col 4
</th>
<th class="col-sm-1">Col 5
</th>
<th class="col-sm-1">Col 6
</th>
</tr>
<tr>
<td>ILK-AK Garching
</td>
<td>Einen guten Titel zu finden ist eigentlich eine Diskussion …
</td>
<td>Eine wunderbare Heiterkeit hat meine ganze Seele eingenommen, gleich den süßen Frühlingsmorgen, die ich mit ganzem Herzen genieße. Ich bin allein und…
</td>
<td>Niedrig
</td>
<td>
<time datetime="2014-07-18T12:03:38.9570000">18.07.2014 12:03</time>
</td>
<td>
<time datetime="2014-08-20T14:15:39.3830000">20.08.2014 14:15</time>
</td>
</tr>
<tr>
<td>ILK-AK Garching
</td>
<td>Zeta-Kafka ist, gleich einem Manifest, pompös und glorreich
</td>
<td>Jemand musste Josef K. verleumdet haben, denn ohne dass er etwas Böses getan hätte, wurde er eines Morgens verhaftet. »Wie ein Hund!« sagte er, es wa…
</td>
<td>Niedrig
</td>
<td>
<time rel="timeago" datetime="2014-08-20T13:41:22.3500000">20.08.2014 13:41</time>
</td>
<td>
<time rel="timeago" datetime="2014-08-20T14:16:39.8170000">20.08.2014 14:16</time>
</td>
</tr>
<tr>
<td>ILK-AK Garching
</td>
<td>Tests von mechanischen Apparaten sind grundsätzlich erwünsc…
</td>
<td>Er hörte leise Schritte hinter sich. Das bedeutete nichts Gutes. Wer würde ihm schon folgen, spät in der Nacht und dazu noch in dieser engen Gasse mi…
</td>
<td>Mittel
</td>
<td>
<time datetime="2014-08-20T13:41:51.0870000">20.08.2014 13:41</time>
</td>
<td>
<time datetime="2014-08-20T14:18:21.2200000">20.08.2014 14:18</time>
</td>
</tr>
</tbody>
</table>
CSS
/* seo friendly tables */
.div-table {
display: table;
/* Defines a Table */
font-size: 14px;
border-bottom: 1px solid #dddddd;
color: #8d8d8d;
margin: 0;
width: 100%;
}
.table-container {
display: table;
width: 100%;
}
.table-head {
display: table-header-group;
/* Defines a table header group */
font-weight: 600 !important;
text-align: center;
border: solid 1px #ddd;
color: #333;
background: rgb(242, 242, 242);
font-size: inherit;
vertical-align: middle;
}
.table-head .column {
/* Column inside the table-head */
background: #f2f2f2;
color: #7d7d7d;
border: solid 1px #ddd;
}
.table-row {
display: table-row;
/* Defines a table row */
padding: 3px 6px;
color: #333;
border-collapse: collapse;
text-align: center;
vertical-align: middle;
}
.table-row .column:nth-child(1) {
/* First column in a row */
border-left: 1px solid #eeeeee;
}
.table-row:last-child .column {
/* column in a last row */
border-bottom: none;
}
.table-row:hover {
background: #f9f9f9;
}
.column {
display: table-cell;
/* Defines a table cell */
padding: 8px 3px;
color: #333;
border-bottom: 1px solid #eeeeee;
border-right: 1px solid #eeeeee;
vertical-align:middle;
}
/* Responsive table */
@media all and (max-width:768px) {
.div-table, .table-row, .column, .column:before {
display: block;
/* Converts a table, table row, table column and table column:before into a block element */
}
.div-table, .table-row .column:last-child {
border-bottom: none;
}
.table-head {
position: absolute;
/* Hides table head but not using display none */
top: -1000em;
left: -1000em;
}
.table-row {
border: 1px solid #eeeeee;
margin: 20px 0;
}
.table-row .column {
border-right:none;
text-align: left;
}
.table-row .column:nth-child(1) {
/* first column of the row */
border-left: none;
border-right: none;
}
.table-row .column:last-child {
/* last column of the row */
border-right: none;
}
.table-row:last-child .column, .column {
/* Column in the last row and column */
border-bottom: 1px solid #eeeeee;
}
.table-row:hover {
background: #fff;
}
.column:before {
/* prints the value of data-label attribute before the column data */
font-weight: bold;
padding-right: 20px;
font-size: 12px;
content:"" attr(data-label)"";
/* call the attribute value of data-label and adds a string // */
}
.column:hover {
background: #f9f9f9;
}
}
Код jQuery
$(document).ready(function () {
var gridClass = $('.table');
// counts total number of td in a head so that we can can use it for label extraction
var head_col_count = $(gridClass).find('tbody th').size();
// loop which replaces td
for (i = 0; i <= head_col_count; i++) {
// head column label extraction
var head_col_label = $(gridClass).find('tbody th:nth-child(' + i + ')').text();
// replaces td with <div class="column" data-label="label">
$(gridClass).find('tr td:nth-child(' + i + ')').replaceWith(function () {
return $('<div class="column" data-label="' + head_col_label + '">').append($(this).contents());
});
}
// replaces table with <div class="table">
$(gridClass).replaceWith(function () {
return $('<div class="div-table">').append($(this).contents());
});
// replaces thead with <div class="table-head">
$('.div-table tbody tr:first-child').replaceWith(function () {
return $('<div class="table-head">').append($(this).contents());
});
// replaces tbody with <div class="table-container">
$('.div-table tbody').replaceWith(function () {
return $('<div class="table-container">').append($(this).contents());
});
// replaces tr with <div class="table-row">
$('.div-table tr').replaceWith(function () {
return $('<div class="table-row">').append($(this).contents());
});
// replaces th with <div class="column">
$('.div-table th').replaceWith(function () {
return $('<div class="column">').append($(this).contents());
});
});
Здесь можно найти полноэкранную демонстрацию . Jsfiddle.net edit ссылка.
Однако, если вы хотите перейти с текущей разметкой html, вам нужно немного изменить script.
Ответ 3
Вы можете сделать это чисто с помощью нескольких строк css...
@media all and (max-width:768px) {
.calculator tr { display: table; width:100%; }
.calculator td { display: table-row; }
}
.calculator - это класс, используемый для таблицы:
<table class="calculator">
Я использую это, чтобы быстро изменить таблицу, которую я использую для входов калькулятора для более разумного вида при просмотре между мобильным/рабочим: живой пример здесь хотя различие лучше всего просматривается мобильным устройством и рабочим столом вдоль друг друга (не все мои мобильные скрипты перегружены в настольный браузер, поэтому общий дизайн может выглядеть нечетным, если вы просто просматриваете браузер на рабочем столе и сводите к минимуму, но ячейки станут строки и т.д.).
Кроме того, вы можете добавить ярлык span/label в ячейку и сделать это
display:table-cell;
и сделайте таблицу блоком, если хотите, этот подход намного более легкий и останавливает необходимость использования javascript.