CSS Tables
The look of an HTML table can be greatly improved with CSS:
| Company | Contact | Country |
|---|---|---|
| Alfreds Futterkiste | Maria Anders | Germany |
| Berglunds snabbköp | Christina Berglund | Sweden |
| Centro comercial Moctezuma | Francisco Chang | Mexico |
| Ernst Handel | Roland Mendel | Austria |
| Island Trading | Helen Bennett | UK |
| Königlich Essen | Philip Cramer | Germany |
| Laughing Bacchus Winecellars | Yoshi Tannamuri | Canada |
| Magazzini Alimentari Riuniti | Giovanni Rovelli | Italy |
Try it Yourself »
Table Borders
To specify table borders in CSS, use the border property.
| Firstname | Lastname |
|---|---|
| Peter | Griffin |
| Lois | Griffin |
Example
table, th, td <
border: 1px solid;
>
Full-Width Table
| Firstname | Lastname |
|---|---|
| Peter | Griffin |
| Lois | Griffin |
Example
table <
width: 100%;
>
Double Borders
To remove double borders, take a look at the example below.
Collapse Table Borders
The border-collapse property sets whether the table borders should be collapsed into a single border:
| Firstname | Lastname |
|---|---|
| Peter | Griffin |
| Lois | Griffin |
Example
table <
border-collapse: collapse;
>
| Firstname | Lastname |
|---|---|
| Peter | Griffin |
| Lois | Griffin |
Printing a html table
You can modify it to your needs.
In fact it opens a new window containing this element and prints it.
answered Apr 16, 2012 at 12:08
4,326 9 9 gold badges 48 48 silver badges 77 77 bronze badges
One approach is to open the table in a new page. You can do this with a javascript submit of a form to the new page, passing along all the variables you will need to build your table.
Then put the code to generate the table on the new page along with your button. If you don’t want a button, you can still invoke the print function by simply referring to your javascript function within your html code:
You can also open your table in a new page using the javascript window.open() method. This is a good approach if you don’t have too many variables to pass to the new window. You can pass a few small things via url variables, which you can set up in your javascript function.
I have also used an approach where I stay on the same page and the user can click on something to remove the display of everything but the table. This is done by wrapping the removable stuff in a div
stuff
When the user does a click, the javascript function that is fired sets the display for that id to «none».
document.getElementById('remove').style.display = 'none';
A second click restores the display. The click doesn’t have to be on a button. I have used it on a report heading, so that everything would disappear except the report itself. You could put it on one of your table cells.
In any case, the window.print() method will only open a window for the printer; the user can then set up the print job as he/she wishes, make sure the printer is on, etc.
table-layout
The table-layout CSS property sets the algorithm used to lay out cells, rows, and columns.
Try it
Syntax
/* Keyword values */ table-layout: auto; table-layout: fixed; /* Global values */ table-layout: inherit; table-layout: initial; table-layout: revert; table-layout: revert-layer; table-layout: unset;
Values
The automatic table layout algorithm is used. The widths of the table and its cells are adjusted to fit the content. Most browsers use this algorithm by default.
The fixed table layout algorithm is used. When using this keyword, the table’s width needs to be specified explicitly using the width property. If the value of the width property is set to auto or is not specified, the browser uses the automatic table layout algorithm, in which case the fixed value has no effect.
The fixed table layout algorithm is faster than the automatic layout algorithm because the horizontal layout of the table depends only on the table’s width, the width of the columns, and borders or cell spacing. The horizontal layout doesn’t depend on the contents of the cells because it depends only on explicitly set widths.
In the fixed table layout algorithm, the width of each column is determined as follows:
- A column element with explicit width sets the width for that column.
- Otherwise, a cell in the first row with explicit width determines the width for that column.
- Otherwise, the column gets the width from the shared remaining horizontal space.
With this algorithm the entire table can be rendered once the first table row has been downloaded and analyzed. This can speed up rendering time over the «automatic» layout method, but subsequent cell content might not fit in the column widths provided. Cells use the overflow property to determine whether to clip any overflowing content, but only if the table has a known width; otherwise, they won’t overflow the cells.
Formal definition
| Initial value | auto |
|---|---|
| Applies to | table and inline-table elements |
| Inherited | no |
| Computed value | as specified |
| Animation type | discrete |
Formal syntax
table-layout =
auto |
fixed
Examples
Fixed-width tables with text-overflow
This example uses a fixed table layout, combined with the width property, to restrict the table’s width. The text-overflow property is used to apply an ellipsis to words that are too long to fit. If the table layout were auto , the table would grow to accommodate its contents, despite the specified width .
HTML
table> tr> td>Edtd> td>Woodtd> tr> tr> td>Alberttd> td>Schweitzertd> tr> tr> td>Janetd> td>Fondatd> tr> tr> td>Williamtd> td>Shakespearetd> tr> table>
CSS
table table-layout: fixed; width: 120px; border: 1px solid red; > td border: 1px solid blue; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; >
Result
Specifications
| Specification |
|---|
| Cascading Style Sheets Level 2 Revision 2 (CSS 2.2) Specification # width-layout |
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
- Edit the page on GitHub.
- Report the content issue.
- View the source on GitHub.
This page was last modified on Jul 6, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
- Product help
- Report an issue
Our communities
Developers
- Web Technologies
- Learn Web Development
- MDN Plus
- Hacks Blog
- Website Privacy Notice
- Cookies
- Legal
- Community Participation Guidelines
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Как распечатать таблицу
и их на бумаге не видно. Проблема только с правым n-1 столбцом. Часть его рамки справа не выводится, т.к. столбец n для печати не нужен.
2. Ctrl+P показывает, что страница одна, хотя если сказать напр. 5, то выводит 5, т.е. игра в телепатию
3. Шапка таблицы выводится только на первой странице
Заранее благодарен всем за помощь!
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Как распечатать таблицу
Длинная и широкая таблица, нужно распечатать. Несколько проблем. 1. Некоторые столбцы нужны.
Как распечатать расчетную таблицу с отображением формул
ЗАДАНИЕ 3. (MS Excel) 1. Создать в MS Excel расчетную таблицу с обрамлением (границы внешние и.
Распечатать таблицу
Условие: Распечатать таблицу, содержащую номера, фамилии и оценки студентов, получивших хотя бы.

Распечатать таблицу построчно
Добро всем :senor: Когда мне надо распечатать данные с одной строки то я считав данные отображаю.
Регистрация: 18.04.2014
Сообщений: 56
Причем здесь JavaScript?
Приведите полный пример своего кода.
Регистрация: 02.12.2015
Сообщений: 620
PticaOgnennaya, реальный код слишком длинный будет. Из базы поднимается не мало строк и идет генерация таблицы. Сейчас сделаю на десяток строк статический аналог
Добавлено через 1 час 11 минут
PticaOgnennaya,
Нарисовал
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
html> head> meta charset="utf-8"> title>Untitled Document/title> /head> body> table id="tab1" border="1" cellspacing="5" cellpadding="3"> tbody id="t1"> tr> td> п/п/td> td> поставщик/td> td> товар/td> td> цена поставщика/td> td> цена+%/td> td> получено/td> td> остаток/td> td> размещено/td> /tr> tr> td> 1/td> td id="L354C001"> продавец №1/td> td id="L354C002"> утюги/td> td id="L354C003"> 100/td> td id="L354C004"> 150/td> td id="L354C005"> 1000/td> td id="L354C006"> 870/td> td id="L354C007"> склад №1/td> /tr> tr> td> 2/td> td id="L357C001"> продавец №2/td> td id="L357C002"> чайники/td> td id="L357C003"> 300/td> td id="L357C004"> 250/td> td id="L357C005"> 5000/td> td id="L357C006"> 1700/td> td id="L357C007"> склад №3/td> /tr> /tbody> /table> /body> /html>
Левая и правая колонки не нужны(реально еще внутри пару колонок пропускаются)
С левой колонкой и внутренними нет проблем вообще. С правой проблема. Если отрезаю «размещено», пропадает правая граница от «остаток».
На печать нужно вывести около 20 страниц. Заголовок только на первой странице есть.
С Ctrl+P вообще не представляю как решить проблему.
Кроме того, есть проблема с браузером, если специально настроить печать, то в заголовке будет адресная строка из браузера. Бухгалтеру она нужна как рыбке зонтик.