センターに配置したテキストの両側を線で挟むやつ

Ads

Result


よくあるやつです。ベーシックな方法、spanを使わないパターン、背景(白)を使わないパターンもあります

css

h2.background {/*ベース*/
  position: relative;
  z-index: 1;
}
h2.background:before {/*疑似要素を追加してborderを作る*/
  border-top: 2px solid #dfdfdf;
  content: "";
  margin: 0 auto;
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  bottom: 0;
  width: 95%;
  z-index: -1;
}
h2.background span {/*疑似要素で追加したborderを隠すため、背景を加える*/
  background: #fff;
  padding: 0 15px;
}
h2.double:before {
  border-top: none;
}
h2.double:after {/*二重線はbox-shadowを使う*/
  border-bottom: 1px solid blue;
  box-shadow: 0 1px 0 0 red;
  content: "";
  margin: 0 auto;
  position: absolute;
  top: 45%;
  left: 0;
  right: 0;
  width: 95%;
  z-index: -1;
}
h2.no-background {/*背景色を使わないパターン*/
  position: relative;
  overflow: hidden;
}
h2.no-background span {
  display: inline-block;
  vertical-align: baseline;
  position: relative;
  padding: 0 20px;
}
h2.no-background span:before,
h2.no-background span:after {/*spanそのものの両端に疑似要素を加える*/
  content: '';
  display: block;
  width: 1000px;
  position: absolute;
  top: 0.73em;
  border-top: 1px solid red;
}
h2.no-background span:before {
  right: 100%;
}
h2.no-background span:after {
  left: 100%;
}
h2.no-span {/*spanもない場合*/
  display: table;
  white-space: nowrap;
}
h2.no-span:before,
h2.no-span:after {/*テキストに疑似要素を加えてdisplay: table;で並べる*/
  border-top: 1px solid green;
  content: '';
  display: table-cell;
  position: relative;
  top: 0.5em;
  width: 45%;
}
h2.no-span:before {
  right: 1.5%;
}
h2.no-span:after {
  left: 1.5%;
}

html

<h2 class="background">線と被るタイトル</h2>

<h2 class="background"><span>線に挟まれたタイトル</span></h2>

<h2 class="background double"><span>二重線に挟まれたタイトル</span></h2>

<h2 class="no-background"><span>線に挟まれたタイトル(背景なし)</span></h2>

<h2 class="no-span">線に挟まれたタイトル(背景もspanもなし)</h2>

via

CSS line behind title text

タイトルとURLをコピーしました