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 5 years have passed since last update.

CSS : 斜め背景の作り方

Posted at

最近よく見る↓のような斜め背景をCSSで実装する方法です。

See the Pen Slant Section by Kazuyoshi Goto (@KazuyoshiGoto) on CodePen.

HTML

<section></section>
<section class="slant-section"></section>
<section></section>

HTMLはsectionなどのレイヤーに slant-section のクラスを付与するだけです。

CSS

slant-section は以下のような記述です。

.slant-section {
  margin: 100px auto;
}
.slant-section:before {
  content: "";
  display: block;
  position: absolute;
  top: -50px;
  z-index: -1;
  width: 100%;
  height: 150%;
  background: #eee;
  transform: skewY(-5deg);
}
.slant-section + section:before {
  content: "";
  display: block;
  position: absolute;
  top: -50px;
  z-index: -1;
  width: 100%;
  height: 100%;
  background: #fff;
  transform: skewY(-5deg);
}

最初に ,slant-section に十分な上下マージンを取っておきます。
斜めにするのでゆったりした余白が必要です。

次に .slant-section の疑似要素 :before にスタイルを設定していきます。
「斜め背景」と言いつつ、は実は背景ではなく:before 要素を平行四辺形に傾けたものなのです。

この実装には以下3つの工夫が必要です。

工夫1: transform: skewY()

transform: skewY(-5deg); で対象の要素を5度傾けた平行四辺形にできます。

しかしこれを単純に .slant-section にかけると、中身のテキストも含めて傾いてしまいます。
そこで次の工夫が必要です。

工夫2: :before要素を平行四辺形にする

.slant-section自体ではなく、.slant-section:beforeを実体化させ、大きな平行四辺形にして .slant-section の後方に配置する手法を取っています。

しかしここで別の課題が発生します。
slant-section 内の増減に柔軟に対応するために、完全なpx固定にせず縦150%を指定していますが、内容量によっては大きくはみ出してしまうのです。

工夫3: 次のsectionにもスタイル指定する

そこで最後の .slant-section + section:before のスタイルがあります。

slant-section の次のレイヤーでも同じような白い平行四辺形を作ることで、グレーの平行四辺形がはみ出してくるのを防いでいます。

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?