HTML/表格

维基教科书,自由的教学读本

表格过去被广泛滥用于页面的布局。在页面任何部位都可以插入表,甚至在表中插入表。相关的tag是<table> - 表, <tr> - 表行, <td> - 表数据, <th> - 表头。

最简单的表[编辑]

例如:

 <table>
 <tr><th>Food</th><th>Price</th></tr>
 <tr><td>Bread</td><td>$2.99</td></tr>
 <tr><td>Milk</td><td>$1.40</td></tr>
 </table>

显示为

FoodPrice
Bread$2.99
Milk$1.40

表标题与表头[编辑]

例如:

<table>
<caption>公式与结果</caption>
<tr><th>Formula</th><th>Result</th></tr>
<tr><td>1 + 1</td><td>2</td></tr>
<tr><td>3 * 5</td><td>15</td></tr>
</table>

显示为:

公式与结果
FormulaResult
1 + 12
3 * 515

边框[编辑]

表格的边框是可选的。在写代码时打开边框很有好处,可以在提交代码时把边框关闭。

The border of this table is 1 pixel wide.


The border on this table is 5 pixels wide.

缺省值为0,即无边框。

border是table tag的一个属性。语法为:

<table border=X> where X is the border size in pixels.

可以指定边框颜色,但这是Internet Explorer的tag专有的属性:

<table bordercolor="#000000">

用CSS指定颜色更好。

高度与宽度[编辑]

默认表的尺寸与其中的数据所占尺寸一样大。

可以给定表的高度与宽度,语法为: <table height=??? width=???> 其中???是像素数或者相对的百分比。

也可以控制表行或单元格的高度宽度: <tr height=80> <td width="50%">

也可以用CSS指定长度、宽度。

单元格间隔与单元格填充[编辑]

如图所示。单元格间隔(Cell Spacing)是在单元格之间的空白区的像素数。单元格填充(Cell Padding)是单元格内部边框至信息区的像素数。

the difference between cellpadding and cellspacing
the difference between cellpadding and cellspacing

二者都是table tag的属性,默认值都是2: e.g. <table border=1 cellspacing=0 cellpadding=0>

单元格的对齐[编辑]

单元格默认对其是水平左对齐、垂直居中对齐。

可以在td或者tr中指定对齐方式。 水平对齐
Syntax:
<td align="position"> where position is left, center, or right

<tr align="position"> where position is left, center, or right

垂直对齐
Syntax:
<td valign="position"> where position is top, middle or bottom

<tr valign="position"> where position is top, middle or bottom

table tag中包含align="left"align="right"并不是对齐其内容,而是影响整张表在页面上的对齐。

bread$2.99
Milk$1.40

bread$2.99
Milk$1.40

跨多行或多列[编辑]

如图:




<-- This row has three table datas


<-- This row has two. The first uses colspan="2"



<-- 使用 rowspan="2"


<-- This row has only two table datas, because its first is being taken up.

背景颜色与图片[编辑]

设定背景颜色:

<td bgcolor="colour">
<tr bgcolor="colour">
<table bgcolor="colour">

可以写颜色名字或十六进制的颜色值。

设定背景图片:

<td background="filename">
<tr background="filename">
<table background="filename">

Column groups[编辑]

总结[编辑]