-3

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."

0

1 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you do not know why, perhaps don't post it as an answer. The explanation is: td:nth-child(2) matches the cell that is the second child of each tr. ::before targets the pseudo-element inserted before the content of the selected <td>
Might be better to have edited your initial question - where, incidentally, you were told about nth-child(2).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.