LoginSignup
0
0

【CSS】要素と要素の間に等間隔で縦線を入れるサンプルコード

Posted at

やりたいこと

下のデザインみたいに、要素と要素の間に等間隔で縦線を入れたい。
image.png
参考「医療法人社団神明会 佐藤歯科医院」 (https://www.dentist-sato.com/)

コード

フレキシブルボックスで要素を横並びにして、擬似要素を使って縦線を入れます。

sample.html
<div class="flexContainer">
    <h1 class="title">ソダシ</h1>
    <p class="description">5歳牝馬</p>
</div>
sample.css
/* フレキシブルボックス */
.flexContainer{
    display: flex;
    align-items: center;
    justify-content: space-around;
}
/* フレキシブルボックスのアイテム */
.title{
    position: relative;
    margin-right: 134px; /* ポイント2 */
}
.description{
    flex-grow: 1; /* ポイント1 */
}
/*** 縦線 ***/
.title::before{
    content: "";
    /* 縦線の色・形 */
    width: 3px;
    height: 36px;
    border-radius: 2px;
    background-color: #dddddd;
    /* 配置場所 */
    position: absolute;
    right: -64px; /* ポイント3 */
}

結果

真ん中に左右の要素から等間隔で縦線が入る。
image2.png

ポイント

ポイント1:『flex-grow: 1』

フレキシブルボックスのアイテムをとりあえずくっつける。

ポイント2:『margin-right: 134px』

くっつけたアイテムの間に隙間をあける。

ポイント3:『right: -64px』

開けた隙間の半分くらいの箇所に縦線を配置する。

補足

ポイント2の隙間を変更すれば、要素間の大きさを調整することができて、変更した場合はmargin-rightの半分の値をポイント3に指定してあげれば調節できる。
ちなみに、リセットCSSを指定している場合はtop指定とか必要かもです。

さいごに

タイトルで"等間隔"と書いてるのに割り算を間違えて、上のサンプルは等間隔じゃないのはすみません。(キャプチャ取り直すのが億劫なのでこのまま公開します。。)

0
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
0
0