Skip to content

Instantly share code, notes, and snippets.

@u1f992
Last active June 17, 2025 14:59
Show Gist options
  • Select an option

  • Save u1f992/e43d26af175deaf930e2e74068dcd7c4 to your computer and use it in GitHub Desktop.

Select an option

Save u1f992/e43d26af175deaf930e2e74068dcd7c4 to your computer and use it in GitHub Desktop.
<style> @page { size: A4; margin-block: 15mm; } :root { counter-reset: section; } h2::before { content: counter(section); inline-size: 2em; text-indent: 0; text-align: center; position: absolute; left: -2em; top: 50%; transform: translateY(-50%); } h2 { height: 100px; background-color: aqua; margin-inline-start: 2em; align-content: center; /* ::before疑似要素のabsoluteの基準をh2にするために必要 */ position: relative; counter-increment: section; } </style>

前のセクション

これは1つ前のセクションの例です。

Section
Heading

この例は、spanなどの子要素を含む見出し要素で、カウンターと見出しを個別に垂直方向の中央寄せにする方法を示しています。カウンターについてはさらに水平方向も中央に寄せています。

h2要素自体は、CSS Box Alignment Module Level 3によって(比較的)新たにブロック要素にも適用できるようになったalign-content: centerで寄せています。一方でカウンターは、親要素のposition: relativeposition: absolute; top: 50%; transform: translateY(-50%);を組み合わせる古い方法で垂直方向の中央に寄せることになります。

カウンターと見出しを横並びにして垂直方向の中央に寄せる方法として、まず思い浮かぶのはフレックスボックスレイアウトでしょう。

h2 {
    height: 100px;
    display: flex;
    align-items: center;
    /* ... */
}

しかし、見出しがspanなどを含む場合は機能しません。フレックスボックスレイアウトはテキストノード「Section」、span要素「H」、テキスト要素「eading」を横並びにしてしまうためです。グリッドレイアウトも同様です。## <span class="container">Section ...</span>とすることで解決することはできますが、すべての見出しをspanで囲むのは標準的なルールとは言えず、現実的ではありません。

この手法は、Markdownの手軽さを保ちつつ目標のレイアウトを実現する、現実的な妥協案といえます。

Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment