1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

はてなブログでソースコードの行番号をCSSだけで表示する

Last updated at Posted at 2022-02-07

はてなブログ上のソースコード表示ですが、行番号はつけられません。

そこで、CSSだけを使って行番号を表示させてみます。ただし、横スクロールを表示してソースコードは改行させないやり方です。

Markdown記法で、次のCSSを貼り付けてください。<style>だけだと有効にならないので、<span>で囲うのが良いそうです。

<span><style>
pre.code {
  /* 行番号の基準をpreの左上にする */
  position: relative;
  /* コードの左側を空ける */
  padding: .25em 0 0 3em;
  /* 横スクロールバーを出して、コードが改行しないようにする */
  white-space: pre;
  overflow-x: scroll;
}
pre.code::before {
  /* 行番号。\aで改行している */
  content: "1\a 2\a 3\a 4\a 5\a 6\a 7\a 8\a 9\a 10\a 11\a 12\a 13\a 14\a 15\a 16\a 17\a 18\a 19\a 20\a 21\a 22\a 23\a 24\a 25\a 26\a 27\a 28\a 29\a 30\a 31\a 32\a 33\a 34\a 35\a 36\a 37\a 38\a 39\a 40\a 41\a 42\a 43\a 44\a 45\a 46\a 47\a 48\a 49\a 50\a";
  /* 行番号の基準をpreの左上にする */
  position: absolute;
  left: 0;
  /* widthを設定するためにblock表示 */
  display: block;
  width: 1.75em;
  /* 行番号の調整 */
  padding-left: .25em;
  color: #c0c0c0;
  text-align: center;
  /* 行番号とコードの間に線を引く */
  border-right: 1px solid #c0c0c0;
}
</style></span>

overflow: hidden;が予め設定されていたので、コードよりも行番号が多い場合は勝手に隠れてくれます。

参考にした記事

ベースにしたのは次の記事です。CSSの説明が詳しくて助かりました。

さらに、content:で行番号を改行するアイデアは次の記事で教えてもらいました。

また、はてなブログのMarkdown記法で<style>が有効にならないことと、その対処はこちらの記事を参考にしました。

記事を書いてくださった皆さん、どうもありがとうございました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?