跨多个元素的连续边框

Continuous border across multiple elements

我正在尝试向代码片段添加行号。它工作正常,除了行号和代码行之间的边界不连续的装饰细节。相反,它有小而难看的间隙。

检查元素似乎没有解释间距。

我也试过摆弄 line-height,但在不显着影响间距的情况下没有任何效果。

pre {
    counter-reset: linenum;
    font-family: "DejaVu Sans Mono";
}

pre code {
    counter-increment: linenum;
}

pre code::before {
    content: counter(linenum);
    display: inline-block;
    width: 3em;
    text-align: right;
    padding-right: 0.5em;
    margin-right: 0.5em;
    color: #888;
    border-right: 1px solid #888;
}
<pre>
<code>Line one</code>
<code>Line two</code>
<code>Line three</code>
</pre>

问题是由 pre 中设置的 font-family 引起的,所以简单的修复方法是删除字体,默认为 monospace

pre {
  counter-reset: linenum;
}

pre code {
  counter-increment: linenum;
}

pre code::before {
  content: counter(linenum);
  display: inline-block;
  width: 3em;
  text-align: right;
  padding-right: 0.5em;
  margin-right: 0.5em;
  color: #888;
  border-right: 1px solid #888;
}
<pre>
<code>Line one</code>
<code>Line two</code>
<code>Line three</code>
</pre>

如果你想保留字体,那么你有几种方法可以实现你想要的:

  • pre
  • 中设置display: grid

pre {
  counter-reset: linenum;
  font-family: "DejaVu Sans Mono";
  display: grid;
}

pre code {
  counter-increment: linenum;
}

pre code::before {
  content: counter(linenum);
  display: inline-block;
  width: 3em;
  text-align: right;
  padding-right: 0.5em;
  margin-right: 0.5em;
  color: #888;
  border-right: 1px solid #888;
}
<pre>
<code>Line one</code>
<code>Line two</code>
<code>Line three</code>
</pre>

  • pre
  • 中设置 display: flex & flex-direction: columnm

pre {
  counter-reset: linenum;
  font-family: "DejaVu Sans Mono";
  display: flex;
  flex-direction: column
}

pre code {
  counter-increment: linenum;
}

pre code::before {
  content: counter(linenum);
  display: inline-block;
  width: 3em;
  text-align: right;
  padding-right: 0.5em;
  margin-right: 0.5em;
  color: #888;
  border-right: 1px solid #888;
}
<pre>
<code>Line one</code>
<code>Line two</code>
<code>Line three</code>
</pre>

  • code
  • 中设置 display: table-row

pre {
  counter-reset: linenum;
  font-family: "DejaVu Sans Mono";
  /*just be coeherent with table-row in the child */
  display: table
}

pre code {
  counter-increment: linenum;
  display: table-row
}

pre code::before {
  content: counter(linenum);
  display: inline-block;
  width: 3em;
  text-align: right;
  padding-right: 0.5em;
  margin-right: 0.5em;
  color: #888;
  border-right: 1px solid #888;
}
<pre>
<code>Line one</code>
<code>Line two</code>
<code>Line three</code>
</pre>