htmlcssindexinghtml-tabletablecolumn

How can I add an index to an arbitrary column of a HTML table via CSS?


How can I add an index to an arbitrary column of a HTML table via CSS? In other words get 0, 1, 2 here, without actually having to type them in:

<!DOCTYPE html>
<html>
<head><title>test</title></head>
<body>
 <table border="1">
  <tr><td></td><td>0</td><td></td></tr>
  <tr><td></td><td>1</td><td></td></tr>
  <tr><td></td><td>2</td><td></td></tr>
</table>

P.S., please just tell me how to add the index to say, that middle column. Please don't fluff it up with extra CSS. "I left my car for a muffler change. When I came back I couldn't even find it in the parking lot because they gave it a new paint job."


Solution

  • Here's your answer:

    <!DOCTYPE html>
    <html>
    <head>
     <title>test</title>
     <style type="text/css">
     table { counter-reset: row-counter; }
     tbody tr { counter-increment: row-counter; }
     tr td:nth-child(2)::before { content: counter(row-counter);}
     </style>
    </head>
    <body>
     <table border="1">
      <tr><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td></tr>
      <tr><td></td><td></td><td></td></tr>
    </table>
    

    All I know is it works. Don't ask me why. Want to start with 1 instead of 0? Better ask a separate question.