过期的 HTML4 Table 属性 cellspacing cellpadding 等在 HTML5 中的等价写法

介绍了过期的 HTML4 Table 属性 cellspacing cellpadding align 在 HTML5 中的等价写法。

目录

在 html4 中创建 table 时经常会用到 cellspacing,cellpadding,align 等属性,比如如下的一个示例:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>table in html4</title>
</head>
<body>
<table cellspacing="2" cellpadding="4" align="center" border="1" style="border: 1px solid black;border-collapse: collapse;">
<caption>html4 table</caption>
<tr>
<td>html4</td>
<td>html4</td>
<td>html4</td>
</tr>
<tr>
<td>html4</td>
<td>html4</td>
<td>html4</td>
</tr>
</table>
</body>
</html>

效果则如下: image 但当我们把 doctype 改为 html5 时,一些属性会被提示已经过期(obsolete)了。比如在 eclipse 的 html 编辑器中,就有如下一些警告提示:

image

比如说:“Attribute (align) is obsolete. Its use is discouraged in HTML5 documents.”

大意为:“属性(align)已经过期了,不鼓励在 html5 文档中使用。”

这些过期的属性值可以在 w3c 的网站上查到:

参考:https://www.w3.org/TR/html5/obsolete.html
如果不使用这些过期的属性,警告自然也会消除,但效果上也会发生变化:

image

那么要达成这些效果,在 html5 中要怎么做呢?

下面给出 html5 中的等价写法:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" >
<title>table in html5</title>
<style>
/* cellspacing */
table { border-spacing: 2px; }

/* cellpadding */
th, td { padding: 4px; }

/* align (center) */
table { margin: 0 auto; }
</style>
</head>
<body>
<table border="1" style="border: 1px solid black;border-collapse: collapse;">
<caption>html5 table</caption>
<tr>
<td>html5</td>
<td>html5</td>
<td>html5</td>
</tr>
<tr>
<td>html5</td>
<td>html5</td>
<td>html5</td>
</tr>
</table>
</body>
</html>

具体的讲,

  • cellspacing 可以用 border-spacing 代替。
  • cellpadding 可以用 th 和 td 的 padding 代替。
  • align=“center”则可以用 margin: auto 代替。
参考:http://stackoverflow.com/questions/6048913/in-html5-with-respect-to-tables-what-replaces-cellpadding-cellspacing-valign