I have a table and I want to use the CSS ::before pseudo element with a counter to add a row number to the first td
of every row. My issue is that if the first td wraps the second line starts under the number, and I would like it to start inline with the text above it. Can this be done with just CSS?
Example:
Edit
https://jsfiddle.net/3yL19zde/
HTML:
<table>
<tr>
<td>Some really long text that wraps to a second line...</td>
<td>Some other column</td>
<td>A third column</td>
</tr>
<tr>
<td>Some really long text that wraps to a second line...</td>
<td>Some other column</td>
<td>A third column</td>
</tr>
</table>
CSS:
table {
width: 480px;
}
table td {
vertical-align: text-top;
}
table tr {
counter-increment: rowNumber;
}
table tr td:first-child::before {
content: counter(rowNumber);
min-width: 1em;
margin-right: 0.5em;
font-weight: bold;
}
The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.
A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.
In CSS, ::after creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Just use the CSS type selector p and set the text-indent property to the value you want. In the example below, let's use a percentage. It will only indent the first line by default.
I would insert the pseudo-element at the beginning of the row instead of inside the first cell, so that it can be displayed as an independent table-cell
:
table {
width: 500px;
}
tr {
counter-increment: row;
}
tr::before {
content: counter(row);
display: table-cell;
font-weight: bold;
}
tr::before, td {
border: 1px dotted #888;
padding: 5px;
}
<table>
<tr>
<td>Some really long text that wraps to a second line...</td>
<td>Some other column</td>
<td>A third column</td>
</tr>
<tr>
<td>Some really long text that wraps to a second line...</td>
<td>Some other column</td>
<td>A third column</td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With