Search code examples
htmlcsscss-counter

How to create an enumerated tabular environment in HTML/CSS?


I need to display some data in an HTML page in a three-column, tabular, enumerated environment, like this:

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
  • No horizontal or vertical rules are necessary.
  • Each piece of data is in a left-aligned "box", so if any text needs to wrap, it still stays in its column.

Is there a clean HTML or CSS solution for presenting enumerated tabular environments?


Solution

  • You can make use of the CSS Counter functionality to auto-generate the numbers like shown in the below example:

    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

    Note:

    1. As per Can I Use, CSS Counters are supported by lower versions of IE also.
    2. If the data is really tabular data as you have mentioned then there is nothing wrong in using the table elements itself.
    3. We are doing a counter-reset whenever a table tag is encountered to make sure that each row in a new table always starts with 1. If the numbering has to continue into a data in another table, then we can reset the counter at the common parent's level (or if none then at body).
    4. Tested in IE (v8 to v10), Firefox, Opera and Chrome and works exactly the same in all of them. JS Fiddle doesn't open properly in IE lower versions, so you can use this JS Bin sample for demo.