gpt4 book ai didi

css - 将代码行号与 CSS 对齐

转载 作者:行者123 更新时间:2023-12-04 21:57:49 26 4
gpt4 key购买 nike

我正在尝试使用纯 CSS 方法(无 javascript)在我的网站( https://qscintilla.com/custom-lexer-example/ )的代码片段中插入行号:

enter image description here

正如您在上面的屏幕截图中看到的,我正在 Wordpress 中构建我的网站。我使用最新 Wordpress 版本中的“附加 CSS”功能来插入自定义 CSS。这是我的自定义 CSS:

pre{
counter-reset: line;
}
code{
counter-increment: line;
}
code:before{
content: counter(line);
display: inline-block;
border-right: 1px solid #ddd;
padding: 0 .5em;
margin-right: .5em;
color: #888;
-webkit-user-select: none;
}

当我像这样在我的 HTML 中插入代码片段时,它工作得很好:
<pre>
<code> This is my first codeline </code>
<code> This is my second codeline </code>
<code> This is my third codeline </code>
<code> This is my fourth codeline </code>
</pre>

不幸的是,当代码行达到两位数时,行号没有正确对齐。让我们放大问题:

enter image description here

当然,代码行从两位数跳到三位数时也会出现同样的问题

我怎样才能解决这个问题?

最佳答案

如果你想要一个纯 CSS 解决方案,只有一种方法:使用固定宽度的解决方案,即在 ::before 上显式声明一个宽度。伪元素。但是,这种方法永远不会过时,因为您必须考虑计数器可能会遇到 3、4 或更多位数的情况。

pre {
counter-reset: line;
}

code {
counter-increment: line;
}

code::before {
content: counter(line);
display: inline-block;
width: 1.5em; /* Fixed width */
border-right: 1px solid #ddd;
padding: 0 .5em;
margin-right: .5em;
color: #888;
-webkit-user-select: none;
}
<pre>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
<code>Code</code>
</pre>

关于css - 将代码行号与 CSS 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43962371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com