如何使用 CSS 格式化 HTML 表格以进行打印?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11573115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:44:59  来源:igfitidea点击:

How to format an HTML table using CSS for printing?

htmlcss

提问by Parag

I want to format table using CSS to show an attendance sheet. How do I add CSS styles to the table so that it can be printed?

我想使用 CSS 格式化表格以显示出勤表。如何将 CSS 样式添加到表格中以便可以打印?

回答by Hiren Soni

use following css

使用以下css

table, th, td
{
  border-collapse:collapse;
  border: 1px solid black;
  width:100%;
  text-align:right;
}

also you can use media="print" for print specific layout

您也可以使用 media="print" 打印特定布局

回答by Jukka K. Korpela

Within your style sheet, use

在您的样式表中,使用

@media print {
  /* put your CSS rules if they are to apply in print only */
}

For example,

例如,

@media print {
   * { color: black; background: white; }
   table { font-size: 80%; }
}

The details depend on the types of problems you expect to have with printing your specific table. Generally, if you have set fixed column widths (e.g. in pixels), you probably need to reconsider this part of your design. If you are using colors to convey essential information (e.g., red cell standing for absence, green for presence), you need to reconsider this decision.

详细信息取决于您希望打印特定表格时遇到的问题类型。通常,如果您设置了固定的列宽(例如以像素为单位),您可能需要重新考虑设计的这一部分。如果您使用颜色来传达基本信息(例如,红色代表缺席,绿色代表存在),您需要重新考虑这个决定。

回答by Random Guy

Use media="print"attribute for your CSS stylesheet to have print specific layout.

使用media="print"CSS 样式表的属性来打印特定的布局。

回答by Luis Felipe de Melo

You can also use

你也可以使用

body {
-webkit-print-color-adjust:exact;
}

回答by Adok Achar

you can add media specific css styles to a page using the @media Rule

您可以使用 @media 规则将特定于媒体的 css 样式添加到页面

for example , @media screenwill use the styles for computer screens and @media printis used for printers.

例如,@media screen将使用计算机屏幕的样式并@media print用于打印机。

using @media allwill make sure your styles are applied to all media type devices

using@media all将确保您的样式应用于所有媒体类型设备

follow linkfor more on media types

点击链接了解更多关于媒体类型的信息

回答by spectrum3900

Correct all good answers.

纠正所有好的答案。

What I would do is to make a specific css file just for print and attach it to the page:

我要做的是制作一个特定的 css 文件只用于打印并将其附加到页面:

<link href='/css/theme-print.css' rel='stylesheet' media="print" type='text/css' />