- Table Text
- Whole Table
- Table Row
- Table Text with CSS Classes
- Colorizing a HTML Table
- Background color of the cell
- Font color
- HTML color codes
- Синтаксис
- Пример
- Результат
- Пример с атрибутом colspan
- Результат
- Пример с атрибутом rowspan
- Результат
- Атрибуты
- Как добавить стиль к тегу ?
- Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- Цвет текста внутри тега :
- Стили форматирования текста для тега :
- Другие свойства для тега :
Table Text
In HTML, table text is the text that is located within an HTML table. Often you will want your table text to appear different to the other text on the page. This page contains table text codes for applying styles to the text within your HTML tables.
To style the text within a table, you use the same CSS properties that you would use in styling any text. The thing to remember is that, you need to know which HTML element to apply the style against. For example, to change the text color across the whole table, use the color property against the tag. But to change the text color in only the table header, you should only apply that property to the element, or alternatively, to each individual tag (or the tag that contains the table headers).
Below are some examples of applying styles against table text in HTML.
Whole Table
This example applies various styles against the text in the whole table. Therefore, I apply the styles against the tag.
Table Row
To change the text style in a whole table row, you can apply the CSS against the tag.
Table Text with CSS Classes
Using CSS classes is a more efficient way of setting your styles. You simply create a class (using a name of your choosing), then apply styles against that class. Then you can refer to that class from anywhere within your HTML document.
Here’s an example of using an embedded style sheet to define the styles of your HTML tables. Note that the styles are set in between the opening and closing tags.
Colorizing a HTML Table
In this post you will be shown how you can edit the font color and the background color of the cells as you wish.
In order to make a HTML table visually appealing, you can colorize it. In this post you will be shown how you can edit the font color and the background color of the cells as you wish.
For example, I added a table of the current Formula1 team standings down below. To recognize the teams more easily, I colorized the cells in the team colors.
Additionally, I changed the font color of «Ferrari» and «Red Bull» to white, in order to get a better contrast.
Team | Points |
---|---|
Mercedes | 438 |
Ferrari | 288 |
Red Bull | 244 |
The HTML code for this table looks like this:
Team Points Mercedes 438 Ferrari 288 Red Bull 244
Background color of the cell
In order to change the background color of a cell to silver, you have to change the brackets to . After that, you enter the regular text that should be displayed in the cell.
Font color
Changing the font color to white demands changing the brackets to . In the given example this was combined with a new background color. Several attributes are seperated by blank characters:
HTML color codes
The colors in HTML can be adressed in different ways. On one hand it is possible to just name the color, like «silver» or «darkblue». This works well, but results in a relatively small color palette.
It is also possible to use HTML color codes. This way, the color can be defined exactly, like I did above with «Ferrari». In this case it is not simply «red», but the color code #DF0101. On the website HTML-Color-Codes you can get the color code for any color.
HTML тег
Обратите внимание, что все строки таблицы содержат одинаковое количество ячеек, которое соответствует количеству ячеек самой длинной строки. Если в одной строке содержится меньше ячеек, чем в других строках, то браузер автоматически заполнит строку, помещая пустые ячейки в конец этой же строки.
Если вам необходимо подчеркнуть, что данные в других ячейках отсутствуют, создайте ячейку без содержимого в необходимом месте.
Добавленные браузером ячейки не имеют рамок, и если они находятся друг за другом, то будут отображаться в виде одной объединенной ячейки.
Синтаксис
Пример
html> html> head> title>Заголовок документа title> style> th, td < padding: 10px; border: 1px solid #666; > style> head> body> table style="width:80%; margin:30px auto; border-collapse:collapse;"> tr style="background-color:#1c87c9; color:#fff;"> th>Месяц th> th>Дата th> tr> tr style="background-color:lightgrey;"> td>Март td> td>10.09.2018 td> tr> tr style="background-color:lightgrey;"> td>Июнь td> td>18.07.2018 td> tr> table> body> html>
Результат
Пример с атрибутом colspan
html> html> head> title>Заголовок документа title> style> th, td < padding: 10px; border: 1px solid #666; > style> head> body> table style="width:80%; margin:30px auto; border-collapse:collapse;"> tr style="background-color:#1c87c9; color:#fff;"> th>Эл. почта компании th> th>Дата th> tr> tr> td style="background-color:#e6ebef;">a href="#">[email protected] a> td> td style="background-color:#e6ebef;">01.09.2017 td> tr> tr style="height:60px; background-color:#e6ebef;"> td colspan="2" valign="bottom" style="background-color:#a3cced;">[email protected]; strong>01.09.2017 strong>span style="font-size:14px;">(received date) span> td> tr> table> body> html>
Результат
Пример с атрибутом rowspan
html> html> head> title>Заголовок документа title> style> th, td < padding: 10px; border: 1px solid #666; > style> head> body> table style="width:80%; margin:30px auto; border-collapse:collapse;"> tr style="background-color:#1c87c9; color:#fff;"> th>Месяц th> th>Год th> tr> tr> td style="background-color:#e6ebef;">Март td> td rowspan="2" style="background-color:#a3cced; text-align:center;">2014 td> tr> tr style="background-color:#e6ebef;"> td style="background-color:#e6ebef;">Июнь td> tr> table> body> html>
Результат
Атрибуты
Атрибут | Значение | Описание | |
---|---|---|---|
abbr | text | Определяет сокращенный вариант содержимого ячейки, либо выступает в роли альтернативного текста. | |
align | left right center justify char | Выравнивает содержимое ячейки данных таблицы. Не поддерживается в HTML5. | |
axis | category_name | Задает группировку ячеек, связанных между собой похожей информацией. Не поддерживается в HTML 5. | |
background | background | Задает фоновый рисунок в ячейке. Не поддерживается в HTML 5. | |
bgcolor | rgb(x,x,x) #xxxxxx colorname | Задает цвет фона ячейки таблицы. Не поддерживается в HTML 5. | |
bordercolor | bordercolor | Задает цвет рамки. Не поддерживается в HTML 5. | |
char | character | Выравнивает содержимое ячейки данных таблицы по заданному символу. Атрибут char используется только если атрибут align = «char». Не поддерживается в HTML 5. | |
charoff | number | Атрибут позволяет произвести выравнивание в ячейке данных с указанного в атрибуте символа вправо или влево. Атрибут charoff используется только, если атрибут align = «char». Не поддерживается в HTML 5. | |
colspan | number | Атрибут определяет количество столбцов, которое ячейка должна охватывать. Значение атрибута должно быть положительным целым числом. Не рекомендуется использовать значения свыше 1000, т.к. они могут быть сокращены до этого числа. Значение по умолчанию 1. | |
headers | header_id | Указывает id одной или нескольких заголовок ячеек, которые определяются HTML тегом | . Атрибут не отображается в браузере, но может быть использован для чтения с экрана или в работе скриптов. |
height | % pixels | Задает высоту ячейки. Не поддерживается в HTML 5. | |
nowrap | nowrap | Указывает, что содержание в ячейке не должно переноситься. Не поддерживается в HTML 5. | |
rowspan | number | Атрибут определяет количество строк, которые ячейка данных должна охватывать. Значение атрибута должно быть положительным целым числом. Не рекомендуется использовать значения свыше 65534, т.к. они могут быть обрезаны до этого числа. Значение по умолчанию 1. | |
scope | col colgroup row rowgroup | Задает способ связывания заголовочной ячейки (HTML тег | ) с ячейками данных в таблице. Не поддерживается в HTML 5. |
valign | top middle bottom baseline | Задает вертикальное выравнивание содержимого в ячейке данных. Не поддерживается в HTML 5. | |
width | % pixels | Задает ширину ячейки данных. Не поддерживается в HTML 5. |
Как добавить стиль к тегу ?
Распространенные свойства для изменения визуальной насыщенности/выделения/размера текста внутри тега :
- CSS свойство font-style задает стиль шрифта: normal | italic | oblique | initial | inherit
- CSS свойство font-family создает приоритетный список названий семейства шрифтов и/или общее имя шрифтов для выбранных элементов.
- CSS свойство font-size задает размер щрифта.
- CSS свойство font-weight устанавливает насыщенность шрифта.
- CSS свойство text-transform задает регистр текста (заглавные или строчные буквы).
- CSS свойство text-decoration устанавливает оформление текста. Оно является сокращенным свойством для text-decoration-line, text-decoration-color, text-decoration-style.
Цвет текста внутри тега :
Стили форматирования текста для тега :
- CSS свойство text-indent указывает размер отступа первой строки в текстовом блоке.
- CSS свойство text-overflow указывает, как будет отображаться пользователю строчный текст, выходящий за границы блока.
- CSS свойство white-space указывает, как будут отображены пробелы внутри элемента.
- CSS свойство word-break указывает перенос строки.
Другие свойства для тега :
- CSS свойство text-shadow добавляет тень к тексту.
- CSS свойство text-align-last выравнивает последнюю строку текста.
- CSS свойство line-height устанавливает межстрочный интервал.
- CSS свойство letter-spacing устанавливает расстояние между буквами/символами в тексте.
- CSS свойство word-spacing устанавливает расстояние между словами в тексте.