Таблицы
Документация и примеры для выбора стиля таблиц (учитывая их преобладающее использование в плагинах JavaScript) Bootstrap.
Обзор
В связи с широким использованием элементов <table> в сторонних виджетах, таких как календари и средства выбора даты, мы сделали так, что таблицы Bootstrap подключены. Добавьте базовый класс .table в любой <table> для расширения стилизацию за счет наших обычных классов, либо классов-модификаторов. Все стили таблиц в Bootstrap не наследуются, то есть любые вложенные таблицы могут быть стилизованы независимо от родительских.
Вот так таблицы, основанные на классе .table, выглядят в базовой разметке таблиц в Bootstrap.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td colspan="2">Larry the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
Варианты
Используйте их для раскраски рядов или отдельных ячеек таблицы.
| Class | Heading | Heading |
|---|---|---|
| Default | Cell | Cell |
| Primary | Cell | Cell |
| Secondary | Cell | Cell |
| Success | Cell | Cell |
| Danger | Cell | Cell |
| Warning | Cell | Cell |
| Info | Cell | Cell |
| Light | Cell | Cell |
| Dark | Cell | Cell |
<!-- On tables -->
<table class="table-primary">...</table>
<table class="table-secondary">...</table>
<table class="table-success">...</table>
<table class="table-danger">...</table>
<table class="table-warning">...</table>
<table class="table-info">...</table>
<table class="table-light">...</table>
<table class="table-dark">...</table>
<!-- On rows -->
<tr class="table-primary">...</tr>
<tr class="table-secondary">...</tr>
<tr class="table-success">...</tr>
<tr class="table-danger">...</tr>
<tr class="table-warning">...</tr>
<tr class="table-info">...</tr>
<tr class="table-light">...</tr>
<tr class="table-dark">...</tr>
<!-- On cells (`td` or `th`) -->
<tr>
<td class="table-primary">...</td>
<td class="table-secondary">...</td>
<td class="table-success">...</td>
<td class="table-danger">...</td>
<td class="table-warning">...</td>
<td class="table-info">...</td>
<td class="table-light">...</td>
<td class="table-dark">...</td>
</tr>
Придание смысла вспомогательным технологиям
Использование цвета как дополнительного инструмента информативности доступно только в визуальной сфере, что ограничивает пользователей вспомогательных технологий, таких как программы чтения с экрана. Убедитесь, что информация, обозначенная цветом, также доступна из самого содержимого (например, видимый текст) или содержится в альтернативных средствах, таких как дополнительный скрытый в классе .visually-hidden текст.
Акцентированные таблицы
Разделенные «полосами» ряды
Добавьте класс .table-striped к <tbody> для разделения «полосками зебры» рядов таблицы.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-striped">
...
</table>
Эти классы также можно добавить в следующие варианты таблиц:
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-dark table-striped">
...
</table>
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-success table-striped">
...
</table>
Ряды с :hover (отзывчивость при наведении)
Добавьте класс .table-hover в <tbody> для активации :hover у рядов таблицы.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-hover">
...
</table>
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-dark table-hover">
...
</table>
Эти :hover ряды также можно комбинировать с «полосатым» вариантом:
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-striped table-hover">
...
</table>
Активные таблицы
Для выделиния ячеек таблицы добавьте класс .table-active.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table">
<thead>
...
</thead>
<tbody>
<tr class="table-active">
...
</tr>
<tr>
...
</tr>
<tr>
<th scope="row">3</th>
<td colspan="2" class="table-active">Larry the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-dark">
<thead>
...
</thead>
<tbody>
<tr class="table-active">
...
</tr>
<tr>
...
</tr>
<tr>
<th scope="row">3</th>
<td colspan="2" class="table-active">Larry the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
Как работают варианты и акцентированные таблицы?
Для акцентированные таблиц (разделенных «полосами» рядов, рядов с :hover и активных таблиц) мы использовали следующие методы для эффективной работы всех наших контекстуальных классов:
- Мы начинаем с установки фона ячейки таблицы с помощью настраиваемого свойства
--bs-table-bg. Затем все варианты таблицы устанавливают это настраиваемое свойство для раскрашивания ячеек таблицы. Таким образом, у нас не будет проблем, если полупрозрачные цвета используются в качестве фона стола. - Затем мы добавляем тень вставки на ячейки таблицы с помощью
box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg);на слой поверх любого указанногоbackground-color. Поскольку мы используем большой разброс и отсутствие размытия, цвет будет монотонным. Так как--bs-table-accent-bgпо умолчанию не установлен, у нас нет тени блока по умолчанию. - Когда добавляются классы
.table-striped,.table-hoverили.table-activeдля--bs-table-accent-bgустанавливается полупрозрачный цвет для раскрашивания фона. - Для каждого варианта таблицы мы генерируем цвет
--bs-table-accent-bgс самым высоким контрастом в зависимости от этого цвета. Например, основной цвет для.table-primaryтемнее, а для.table-darkсветлее. - Цвета текста и границ генерируются одинаково, а их цвета наследуются по умолчанию.
"За кадром" это выглядит так:
@mixin table-variant($state, $background) {
.table-#{$state} {
$color: color-contrast(opaque($body-bg, $background));
$hover-bg: mix($color, $background, percentage($table-hover-bg-factor));
$striped-bg: mix($color, $background, percentage($table-striped-bg-factor));
$active-bg: mix($color, $background, percentage($table-active-bg-factor));
--#{$variable-prefix}table-bg: #{$background};
--#{$variable-prefix}table-striped-bg: #{$striped-bg};
--#{$variable-prefix}table-striped-color: #{color-contrast($striped-bg)};
--#{$variable-prefix}table-active-bg: #{$active-bg};
--#{$variable-prefix}table-active-color: #{color-contrast($active-bg)};
--#{$variable-prefix}table-hover-bg: #{$hover-bg};
--#{$variable-prefix}table-hover-color: #{color-contrast($hover-bg)};
color: $color;
border-color: mix($color, $background, percentage($table-border-factor));
}
}
Границы таблиц
Таблицы с границами
Добавьте класс .table-bordered для создания границ ячеек и таблицы со всех сторон.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-bordered">
...
</table>Для изменения цвета можно использовать утилиты цвета границы:
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-bordered border-primary">
...
</table>Таблица без отображения границ
Добавьте класс .table-borderless для отображения таблицы без рамок.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-borderless">
...
</table>| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-dark table-borderless">
...
</table>Маленькие таблицы
Добавьте класс .table-sm чтобы сделать любую таблицу .table более компактной, сократив размер padding пополам.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-sm">
...
</table>| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-dark table-sm">
...
</table>Вертикальное выравнивание
Ячейки таблицы <thead> всегда выравниваются по вертикали по нижнему краю. Ячейки таблицы в <tbody> наследуют свое выравнивание от <table> и по умолчанию выравниваются по верхнему краю. Используйте классы вертикального выравнивания для повторного выравнивания там, где это необходимо.
| Заголовок 1 | Заголовок 2 | Заголовок 3 | Заголовок 4 |
|---|---|---|---|
Эта ячейка наследует vertical-align: middle; из таблицы |
Эта ячейка наследует vertical-align: middle; из таблицы |
Эта ячейка наследует vertical-align: middle; из таблицы |
Это текст-заполнитель, предназначенный для того, чтобы занять довольно много места по вертикали, чтобы продемонстрировать, как работает вертикальное выравнивание в предыдущих ячейках. |
Эта ячейка наследует vertical-align: bottom; из строки таблицы |
Эта ячейка наследует vertical-align: bottom; из строки таблицы |
Эта ячейка наследует vertical-align: bottom; из строки таблицы |
Это текст-заполнитель, предназначенный для того, чтобы занять довольно много места по вертикали, чтобы продемонстрировать, как работает вертикальное выравнивание в предыдущих ячейках. |
Эта ячейка наследует vertical-align: middle; из таблицы |
Эта ячейка наследует vertical-align: middle; из таблицы |
Эта ячейка выровнена по верхнему краю. | Это текст-заполнитель, предназначенный для того, чтобы занять довольно много места по вертикали, чтобы продемонстрировать, как работает вертикальное выравнивание в предыдущих ячейках. |
<div class="table-responsive">
<table class="table align-middle">
<thead>
<tr>
...
</tr>
</thead>
<tbody>
<tr>
...
</tr>
<tr class="align-bottom">
...
</tr>
<tr>
<td>...</td>
<td>...</td>
<td class="align-top">Эта ячейка выровнена по верхнему краю.</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>
Вложенность
Стили границ, активные стили и варианты таблиц не наследуются вложенными таблицами.
| # | First | Last | Handle | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | Mark | Otto | @mdo | ||||||||||||
|
|||||||||||||||
| 3 | Larry | the Bird | |||||||||||||
<table class="table table-striped">
<thead>
...
</thead>
<tbody>
...
<tr>
<td colspan="4">
<table class="table mb-0">
...
</table>
</td>
</tr>
...
</tbody>
</table>Как работает вложение
Чтобы предотвратить попадание каких-либо стилей во вложенные таблицы, мы используем селектор дочернего комбинатора (>) в нашем CSS. Поскольку нам нужно настроить таргетинг на все td и th в thead, tbody и tfoot, наш селектор без него выглядел бы довольно длинным. Таким образом, мы используем немного странно выглядящий селектор .table > :not(caption) > * > * для таргетинга на все td и th в .table, но без воздействия ни на одну из потенциально вложенных таблиц.
Обратите внимание, что если вы добавите <tr> в качестве прямых дочерних элементов таблицы, <tr> по умолчанию будут заключены в <tbody>, таким образом, наши селекторы будут работать так, как задумано.
Опции таблицы
Заголовок таблицы
Подобно светлым и темным таблицам, используйте классы-модификаторы .table-light или .table-dark чтобы сделать заголовки <thead> светлыми или темно-серыми.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry | the Bird |
<table class="table">
<thead class="table-light">
...
</thead>
<tbody>
...
</tbody>
</table>
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry | the Bird |
<table class="table">
<thead class="table-dark">
...
</thead>
<tbody>
...
</tbody>
</table>
Низ (основание) таблицы
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry | the Bird | |
| Footer | Footer | Footer | Footer |
<table class="table">
<thead>
...
</thead>
<tbody>
...
</tbody>
<tfoot>
...
</tfoot>
</table>Подпись
<caption> действует как заголовок таблицы. Это помогает пользователям программ чтения с экрана найти таблицу, понять, о чем она, и решить, хотят ли они ее прочитать.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry the Bird | ||
<table class="table table-sm">
<caption>List of users</caption>
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>Вы также можете поместить <caption> в начало таблицы с помощью .caption-top.
| # | First | Last | Handle |
|---|---|---|---|
| 1 | Mark | Otto | @mdo |
| 2 | Jacob | Thornton | @fat |
| 3 | Larry | the Bird |
<table class="table caption-top">
<caption>List of users</caption>
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>«Отзывчивые» таблицы
«Отзывчивые» таблицы позволяют таблицам прокручиваться горизонтально. Сделайте любую таблицу таковой для всех экранов и девайсов, добавив класс .table-responsive в класс .table. Или укажите максимальный брейкпойнт, на котором появится данное свойство таблицы, добавив класс .table-responsive{-sm|-md|-lg|-xl|-xxl}.
Вертикальное обрезание/сокращение
«Отзывчивые» таблицы используют overflow-y: hidden, что «обрезает» любой контент, который существует ниже конца верхних краев таблицы. В частности, это может «срезать» выпадающие меню и другие сторонние виджеты.
Всегда «отзывчиво»
Через каждую контрольную точку используйте .table-responsive для горизонтально прокручиваемых таблиц.
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
<div class="table-responsive">
<table class="table">
...
</table>
</div>Специфика брейкпойнтов (контрольных точек)
Используйте .table-responsive{-sm|-md|-lg|-xl|-xxl} когда необходимо создать адаптивные таблицы до определенной брейкпойнта. До этого значения таблицы будут вести себя как обычные таблицы и не будут прокручиваться горизонтально.
Эти таблицы могут выглядеть неработающими, пока их адаптивные стили не будут применяться при определенной ширине области просмотра.
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
sm:
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
md:
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
lg:
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
xl:
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
xxl:
| # | Heading | Heading | Heading | Heading | Heading | Heading | Heading | Heading |
|---|---|---|---|---|---|---|---|---|
| 1 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 2 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
| 3 | Cell | Cell | Cell | Cell | Cell | Cell | Cell | Cell |
<div class="table-responsive">
<table class="table">
...
</table>
</div>
<div class="table-responsive-sm">
<table class="table">
...
</table>
</div>
<div class="table-responsive-md">
<table class="table">
...
</table>
</div>
<div class="table-responsive-lg">
<table class="table">
...
</table>
</div>
<div class="table-responsive-xl">
<table class="table">
...
</table>
</div>
<div class="table-responsive-xxl">
<table class="table">
...
</table>
</div>Sass
Переменные
$table-cell-padding-y: .5rem;
$table-cell-padding-x: .5rem;
$table-cell-padding-y-sm: .25rem;
$table-cell-padding-x-sm: .25rem;
$table-cell-vertical-align: top;
$table-color: $body-color;
$table-bg: transparent;
$table-accent-bg: transparent;
$table-th-font-weight: null;
$table-striped-color: $table-color;
$table-striped-bg-factor: .05;
$table-striped-bg: rgba($black, $table-striped-bg-factor);
$table-active-color: $table-color;
$table-active-bg-factor: .1;
$table-active-bg: rgba($black, $table-active-bg-factor);
$table-hover-color: $table-color;
$table-hover-bg-factor: .075;
$table-hover-bg: rgba($black, $table-hover-bg-factor);
$table-border-factor: .1;
$table-border-width: $border-width;
$table-border-color: $border-color;
$table-striped-order: odd;
$table-group-separator-color: currentColor;
$table-caption-color: $text-muted;
$table-bg-scale: -80%;
Цикл
$table-variants: (
"primary": shift-color($primary, $table-bg-scale),
"secondary": shift-color($secondary, $table-bg-scale),
"success": shift-color($success, $table-bg-scale),
"info": shift-color($info, $table-bg-scale),
"warning": shift-color($warning, $table-bg-scale),
"danger": shift-color($danger, $table-bg-scale),
"light": $light,
"dark": $dark,
);
Кастомизация
- Факторные переменные (
$table-striped-bg-factor,$table-active-bg-factorи$table-hover-bg-factor) используются для определения контраста в вариантах таблиц. - Кроме светлого и темного вариантов таблицы, цвета темы осветляются переменной
$table-bg-level.