2017.02.13
2017.05.15
コーディング
CSSで背景のみをぼかす方法

今回はCSSで背景画像のみをぼかす方法を紹介します。
ぼかすとなると「 filter: blur();」を使うことは簡単に想像できると思いますが、これが少し厄介なんですよね。背景だけには適応できず、内包している要素がすべてぼかされてしまいます。
そこで擬似要素を使用して実現します。
html
<div class="key" style="background-image:url(key.jpg)">
<p><img src="key.jpg" alt=""></p>
</div>
インラインで背景画像の指定
インラインで背景画像の指定をしているのはCMS等でアイキャッチ画像と共通の画像を背景画像に設定することを想定しています。
CSS
.key{
background: no-repeat center center;
background-size: cover;
padding: 30px;
overflow: hidden;
position: relative;
z-index: 0;
}
.key:before{
content: "";
display: block;
position: absolute;
background: inherit;
filter: blur(5px);
top: -5px;
right: -5px;
bottom: -5px;
left: -5px;
z-index: -1;
}
.key p{
text-align: center;
}
.key p img{
height: 500px;
}
background: inherit;
「 background: inherit;」の「inherit」は親要素の設定を引き継ぐ指定です。今回の場合は「.key」の背景設定を引き継いでいます。
参考にしてみてください。
