[CSS]テキストの左右に水平ラインをすぅーーーっと引くスタイルシートのテクニック
Post on:2014年4月21日
sponsorsr
hn, pなどの要素を使ったテキストの左右に、水平ラインを天地中央に配置するスタイルシートのテクニックを紹介します。
HTMLは非常にシンプル、カラーやサイズの調整も簡単、背景画像も問題ありません。

実装のポイントは5つ。
- 画像は使用しない。
- spanなど、余分なHTMLは使用しない。
- フォントのサイズを大きくしても自動で調整される。
- 可変。
- 背景が画像でも水平ラインが綺麗に描かれる。
実際の動作は、下記ページで確認できます。
デモは全てのモダンブラウザ、IE9+でご覧ください。

HTML
HTMLは非常にシンプルで、hnやp要素のみで実装できます。
classを使用すれば水平ライン有り・無しの共存も可能です。
<body> <h2>テキストの左右に</h2> <h3 class="lines-on-sides">水平のラインを描く</h3> </body>
CSS
まずは、Sassのコードから。
水平ラインはlinear-gradientで描かれており、サイズはcalc()を使用しているのでIE9+になります。
.lines-on-sides {
display: table;
text-align: center;
white-space: nowrap;
&:after,
&:before {
content: '';
display: table-cell;
width: 50%;
background: linear-gradient(transparent 50%, currentColor 50%, currentColor calc(50% + 2px), transparent calc(50% + 2px));
background-clip: padding;
}
&:after {
border-left: 1em solid transparent;
}
&:before {
border-right: 1em solid transparent;
}
}
h2 {
font-size: 1.5em;
color: hsl(30, 70, 80);
@extend .lines-on-sides
}
h3 {
font-size: 1em;
color: hsl(30, 70, 20);
}
通常のスタイルシートにすると、こんな感じに。
.lines-on-sides, h2 {
display: table;
text-align: center;
white-space: nowrap;
}
.lines-on-sides:after, h2:after, .lines-on-sides:before, h2:before {
content: '';
display: table-cell;
width: 50%;
background: -webkit-linear-gradient(transparent 50%, currentColor 50%, currentColor -webkit-calc(50% + 1px), transparent -webkit-calc(50% + 1px));
background: -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(50%, currentColor), color-stop(currentColor calc(50% + 1px)), to(transparent calc(50% + 1px)));
background: linear-gradient(transparent 50%, currentColor 50%, currentColor calc(50% + 1px), transparent calc(50% + 1px));
-webkit-background-clip: padding;
background-clip: padding;
}
.lines-on-sides:after, h2:after {
border-left: 1em solid transparent;
}
.lines-on-sides:before, h2:before {
border-right: 1em solid transparent;
}
h2 {
font-size: 1.5em;
color: #f0cca8;
}
h3 {
font-size: 1em;
color: #57330f;
}
文字と水平ラインの間隔なども簡単に調整できます。

デモのデフォルト
:afrer, :beforeのとこの値を変更。
.lines-on-sides:after {
border-left: 1em solid transparent;
}
.lines-on-sides:before {
border-right: 1em solid transparent;
}
「1em」を「0.2em」に変更。

文字と水平ラインの間を狭く

文字と水平ラインの間を広く
また、他にも実装方法があるので、下記ページも参考にしてみてください。
sponsors











