LoginSignup
3
2

More than 3 years have passed since last update.

枠の上に文字を乗せるやり方

Last updated at Posted at 2019-11-05

始めに

枠のあるデザインで以下のような枠線を一部消して文字を置くような実装をしたいときのやり方を記事にしました。

See the Pen 枠の上に文字を乗せる by wintyo (@wintyo) on CodePen.

実装方法

やり方は単純で、以下のようなことをしているだけです。

  • 1px分の白線を上に被せて消しているように見せる
  • ラベルを所定の位置に移動する

この2つのことをそれぞれの要素で行ってもいいですが、ラベル要素から絶対パスで線を引いておくと消す長さを考えなくてもよくなります。

html
<div class="area">
  <div class="area__label">ラベル</div>
  <div class="area__content">コンテンツ</div>
</div>
scss
.area {
  position: relative;
  width: 300px;
  height: 100px;
  border: solid 1px #f00;
  border-radius: 5px;
  background-color: #fee;

  &__label {
    position: absolute;
    top: 0;
    left: 20px;
    font-weight: 600;
    padding: 0 10px;  // paddingを左右にいれて消す線の長さを延ばす
    transform: translateY(-50%);

    &::before {
      position: absolute;
      z-index: -1;  // 何もしないと線が上に来ていたので-1して後ろに回り込ませる
      left: 0;
      bottom: 50%;  // top: 50%だと1pxずれていたのでbottomから計算する
      width: 100%;  // 親要素の幅を参照するため必ず文字分は消せる
      height: 1px;
      background-color: #fff;
      content: '';
    }
  }

  &__content {
    padding: 20px;
  }
}

終わりに

初めてこういったデザインを見るとどうやって実装するのか悩みそうですが、意外と背景色を上に被せて消すというやり方はあります(フキダシとか)。このような実装は知っていると便利なので誰かの役に立てたなら幸いです。

3
2
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
3
2