Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8685

CSS : 斜め背景の作り方

$
0
0

最近よく見る↓のような斜め背景を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の次のレイヤーでも同じような白い平行四辺形を作ることで、グレーの平行四辺形がはみ出してくるのを防いでいます。


Viewing all articles
Browse latest Browse all 8685

Latest Images

Trending Articles