如何在HTML / CSS中创建枚举表格环境?

时间:2014-09-09 07:08:15

标签: html css css-counter

我需要在三列,表格式枚举环境中的HTML页面中显示一些数据,如下所示:

1. elephant           animal               a large animal that
                                           eats leaves
2. fish               animal               an animal that
                                           swims in the ocean
3. cactus             plant                a plant that lives
                                           in dry places
  • 无需水平或垂直规则。
  • 每个数据都在一个左对齐的"框中,所以如果任何文本需要换行,它仍然会保留在其列中。

是否有用于呈现枚举表格环境的干净HTML或CSS解决方案?

2 个答案:

答案 0 :(得分:3)

您可以使用CSS计数器功能自动生成数字,如下例所示:

table{
    counter-reset: rows; /* initalize the counter variable */
}
tr{
    counter-increment: rows; /* increment the counter every time a tr is encountered */
}
td{ /* just for demo */
    vertical-align: top;
    width: 100px;
}
td:first-child:before{ /* add the counter value before the first td in every row */
    content: counter(rows) ". ";
}

Fiddle Demo

注意:

  1. 根据Can I Use,IE的较低版本也支持CSS计数器。
  2. 如果数据确实是您提到的表格数据,那么使用table元素本身并没有错。
  3. 每当遇到counter-reset标记时,我们正在执行table以确保新表中的每一行始终以1开头。如果编号必须继续进入另一个表中的数据,然后我们可以在公共父级别重置计数器(如果没有,则在body)。
  4. 在IE(v8到v10),Firefox,Opera和Chrome中测试过并且在所有这些中完全相同。 JS Fiddle无法在IE较低版本中正常打开,因此您可以使用此JS Bin示例进行演示。

答案 1 :(得分:1)

您可以使用CSS执行此操作:

table {
counter-reset: rowNumber;
}

table tr {
counter-increment: rowNumber;
}

table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
}

Demo fiddle

但我建议JS:

var table = document.getElementsByTagName('table')[0],
rows = table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText';
console.log(text);

for (var i = 0, len = rows.length; i < len; i++){
   rows[i].children[0][text] = i + ': ' + rows[i].children[0][text];
}

Demo fiddle