【问题标题】:Continuous border across multiple elements跨多个元素的连续边框
【发布时间】:2021-01-08 00:42:16
【问题描述】:

我正在尝试将行号添加到代码 sn-p。它正在工作,除了行号和代码行之间的边界不连续的装饰细节。相反,它有小而丑陋的差距。

检查元素似乎无法解释间距。

我也尝试过摆弄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>

【问题讨论】:

  • line-height:0.8 添加到 pre 并将 line-height:1 添加到代码将解决您的问题

标签: css border line-numbers css-counter


【解决方案1】:

问题是由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: flexflex-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>

【讨论】:

  • 谢谢!我在哪里可以阅读更多关于为什么这有效的信息?
  • 这实际上是由您在pre 标签中的font-family 引起的。我已经更新了提到这一点的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多