如何在:: before伪元素之后得到缩进?

时间:2016-06-19 23:54:07

标签: html css css3

我有一个表,我想使用带有计数器的CSS :: before伪元素将行号添加到每行的第一个td。我的问题是,如果第一个td包装第二行从数字开始,我希望它开始与它上面的文本内联。这可以用CSS完成吗?

示例:

Image example of what I would like to accomplish.

修改

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;
}

2 个答案:

答案 0 :(得分:5)

我会在行的开头而不是在第一个单元格内插入伪元素,以便它可以显示为独立的table-cell

&#13;
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这是一种在同一个单元格内完成的方法(使用text-indent和一些填充)。

table {
    counter-reset: rowNumber;
    width: 480px;
}
td {
    border: 1px dotted #888;
}
td:first-child {
    padding-left: 2em;
    text-indent: -2em;
}
td:first-child:before {
    counter-increment: rowNumber;
    content: counter(rowNumber);
    font-weight: bold;
    display: inline-block;
    text-indent: 0;
    width: 2em;
}
<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>