0
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】途中で色の変わる線の作り方。下線と擬似要素の線を重ねる。

Posted at

CSSを使って途中から色が変わる線を作成する方法。下記のようなイメージ。

image.png

考え方

(1)boxの下側に下線を作成し、(2)その上に擬似要素(::after)で作った線を重ねる。

.html
<div class="headline">
  <h2 class="headline_title">title</h2>
  <p class="headline_subtitle">subtitle</p>
</div>
.css
.headline {
  margin: 0 16px;
  color: #333;
  border-bottom: solid 4px #222222;
  position: relative;
}
.headline::after {
  content: "";
  position: absolute;
  width: 80%;
  border-bottom: solid 4px #f47aa9;
  bottom: -4px;
  right: 0px;
}
.headline_title {
  font-size: 22px;
  font-weight: bold;
}
.headline_subtitle {
  font-size: 15px;
}

1. 親要素

::afterで線を重ねるためposition: relative;を指定しておく。

.headline {
  margin: 0 16px;
  color: #333;
  border-bottom: solid 4px #222222;
  position: relative;
}

※注意点
枠線は枠の外側に広がる。このため、擬似要素の線の高さのスタートラインはこの線の太さの分だけ下げる。


## 2. 擬似要素 `position: absolute;`で位置を指定する。

right: 0px; 右端からスタート。
bottom: -4px; 親で作成した線の太さだけ開始位置を下げる。

.headline::after {
  content: "";
  position: absolute;
  width: 80%;
  border-bottom: solid 4px #f47aa9;
  bottom: -4px;
  right: 0px;
}

以上。


おまけ

レスポンシブデザイン

メディアクエリを使って、スマホサイズになった時は文字の太さや線の太さを小さくする。

また、SASS(scss)で記述。

.html
<div class="headline">
  <h2 class="headline_title">title</h2>
  <p class="headline_subtitle">subtitle</p>
</div>

htmlは変更なし。scssのみ追記。

.scss
.headline{
  margin: 0 16px;
  color: #333;
  border-bottom: solid 4px #222222;
  position: relative;
  @media screen and (max-width: 671px) {
    border-bottom: solid 2px #222222;
  }
  &::after{
    content: "";
    position: absolute;
    width: 80%;
    border-bottom: solid 4px #f47aa9;
    bottom: -4px;
    right: 0px;
    @media screen and (max-width: 671px) {
      border-bottom: solid 2px #f47aa9;
      bottom: -2px;
    }
  }
  &_title{
    font-size: 22px;
    font-weight: bold;
    @media screen and (max-width: 671px) {
      font-size: 18px;
    }
  }
  &_subtitle{
    font-size: 15px;
    @media screen and (max-width: 671px) {
      font-size: 12px;
    }
  }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?