
下記に表示されているような斜線の影をつける方法を紹介します
結論から行くと、box-shadow
プロパティを使うのではなく、疑似要素の:before
、プロパティz-index
、background:linear-gradient
を使用するところが肝で、影を表示したい親の後ろに疑似要素を持ってきて表現する方法になります。
HTML
<div class="wrapper"> <div class="inside"> 斜線の影を表現しています。 </div> </div>
Sass
.wrapper { position: relative; max-width: 300px; width: 100%; background-color: #ff9999; color: #fff; padding: 2rem; margin: 40px auto; border-radius: 10px; .inside { text-align: center; font-feature-settings: "palt 1"; } &::before { content: ""; position: absolute; width: 100%; height: 100%; top: 8px; left: 8px; border-radius: 10px; z-index: -1; -webkit-background-size: 4px 4px; -moz-background-size: 4px 4px; background-size: 6px 6px; background-image: -webkit-gradient(linear, 0 0, 100% 100%, color-stop(0.25, #afafaf), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, #17a2ff), color-stop(0.75, #17a2ff), color-stop(0.75, transparent), to(transparent)); background-image: -webkit-linear-gradient(-45deg, #ff9999 25%, transparent 25%, transparent 50%, #ff9999 50%, #ff9999 75%, transparent 75%, transparent); background-image: -moz-linear-gradient(-45deg, #ff9999 25%, transparent 25%, transparent 50%, #ff9999 50%, #ff9999 75%, transparent 75%, transparent); background-image: -ms-linear-gradient(-45deg, #ff9999 25%, transparent 25%, transparent 50%, #ff9999 50%, #ff9999 75%, transparent 75%, transparent); background-image: -o-linear-gradient(-45deg, #ff9999 25%, transparent 25%, transparent 50%, #ff9999 50%, #ff9999 75%, transparent 75%, transparent); background-image: linear-gradient(-45deg, #ff9999 25%, transparent 25%, transparent 50%, #ff9999 50%, #ff9999 75%, transparent 75%, transparent); } }
解説
今回はボックスの中にテキストを入れて、吹き出しや説明欄として使える用になっていますが、ボタンやセクションまるまる囲ったものにも使えると思います。
はじめにclass="wrapper"
の親要素には、position: relative;
を指定します。
次に疑似要素の::before
を親に対して指定します。この時position: absoute;
,z-index: -1;
, background-image: linear-gradient();
を使用します。
※linear-gradient
の詳細は省きますが、45deg
の部分やカラーコードの部分をいじくれば見た目変わります。
ちなみに、疑似要素の::before
,::after
にはcontent
プロパティを指定してあげないと表示されませんので忘れずに。
transparent
で透過させていますが、カラーを指定すれば、ストライプ柄の影表現できます。
※英語で斜線は「Diagonal Line」らしいです。