最近よく見る↓のような斜め背景をCSSで実装する方法です。
See the Pen Slant Section by Kazuyoshi Goto (@KazuyoshiGoto) on CodePen.
HTML
<section>〜</section><sectionclass="slant-section">〜</section><section>〜</section>
HTMLはsectionなどのレイヤーに slant-section
のクラスを付与するだけです。
CSS
slant-section
は以下のような記述です。
.slant-section{margin:100pxauto;}.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
の次のレイヤーでも同じような白い平行四辺形を作ることで、グレーの平行四辺形がはみ出してくるのを防いでいます。