今回は、CSSで「背景画像の上に薄い背景色を敷く方法」について紹介します。
よく出てくる実装なのでまとめました。
【CSS】背景画像の上に薄い背景色を敷く方法
完成形はこちら。
See the Pen
Untitled by ゆーじろー (@yuji64)
on CodePen.
背景画像の上に薄い背景色を敷き、テキストは薄くならないようにしています。
HTML
<div class="box">
<div class="box-inner">
<h1>ダミータイトルです</h1>
</div>
</div>
親要素boxの中に子要素box-innerを用意します。
CSS
.box {
background-image: url(https://yujiromx.com/wp-content/uploads/2022/05/computer-g8779ca928_640.jpg);
background-size: cover;
position: relative;
width: 100%;
padding-top: 35%;
min-height: 400px;
}
.box::before {
width: 100%;
height: 100%;
z-index: 0;
content: "";
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
}
.box .box-inner {
width: 100%;
height: 100%;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
color: #fff;
padding: 50px 20px;
font-size: 20px;
}
親要素boxに背景画像を指定し、boxの擬似要素を使って背景画像の上に薄い背景色を敷きます。
そして子要素box-innerにはレイアウトに関するプロパティを記述するようにします。
あとはz-indexの数値を調整したらOK。
まとめ
以上が、「背景画像の上に薄い背景色を敷く方法」でした。



