LoginSignup
18
17

More than 5 years have passed since last update.

中途半端な罫線付き見出しの実装(CSS)

Posted at

こんな風に、見出し文字の右側に貫く横線が現れるようなデザイン。

image

HTML的にはこのような構成。

<h2>
    <span>はじめに</span>
</h2>

<p>
    こんな風に見出し文字の右側に横線が現れる見出しを作りたい。
</p>

まず、こんな風に組んでみる。

type-1.scss
$main-color: #666;
$font-size: 24px;

.type-1 {
    $h: $font-size;
    $bw: 2px;

    h2 {
        position: relative;

        height: $h;
        line-height: $h;

        font-size: $h;

        &::after {
            content: "";

            display: block;
            position:absolute;

            width: 330px;
            height: $bw;

            right: 0;
            top: $h / 2;

            margin-top: -$bw / 2;

            background-color: $main-color;
        }
    }
}

再掲ですが、以下のように表示されます。横線の長さが決め打ちなのでこれは意図通りではありません。

image

【解決策1】 table-cellを使った方法

type-2.scss
$main-color: #666;
$font-size: 24px;

.type-2 {
    $h: $font-size;
    $bw: 2px;

    h2 {
        display: table;

        position: relative;

        height: $h;
        line-height: $h;

        font-size: $h;

        span {
            display: table-cell;

            white-space: nowrap;

            padding-right: 10px;
        }

        &::after {
            content: "";

            position: relative;
            display: table-cell;

            width: 100%;

            background-color: $main-color;

            transform: scaleY($bw / $h);
        }
    }
}

white-space: nowrap;で改行を抑えられます。

黒い線は長方形のセルをtransform (scaleY)で無理矢理縮めてます。

tranform前:

image

scaleYを付けて、意図通りのレイアウトができました。

image

【解決策2】 overflow:hiddenを使った方法

type-3.scss
$main-color: #666;
$font-size: 24px;

.type-3 {
    $h: $font-size;
    $bw: 2px;

    h2 {
        position: relative;

        font-size: $h;

        line-height: $h;

        white-space: nowrap;

        overflow: hidden;

        &::after {
            content: "";

            display: inline-block;

            position: relative;

            width: 100%;
            height: $bw;

            left: 0;
            bottom: $h / 2 - $bw;

            background-color: $main-color;
        }
    }
}

inline-blockを繋げて、右側の線要素はwidthを100%にし、
overflow: hiddenにすることによりはみ出さないようにします。

これでも意図通りの結果が得られました。

image

デモはこちら

謝辞: 解決策2のアイデアをくれたT. Itabashi氏に感謝します。

18
17
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
18
17