今回はbackgound-imageを使用して、画像に色を重ねてみます。
画像の上にマウスを持っていくと、画像を覆うマスクの色と大きさが変わり文字が浮かんできます。
<html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>デモ</title>
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<!--header-->
<header></header>
<main ontouchstart="">
<div class="backgroundBox">
<div class="Container">
<div class="top"></div>
</div>
</div>
</main>
<!--footer-->
<footer></footer>
</body>
</html>
<ポイント>
・divタグのtopにいろいろcssを適用していきます。
<css>
※index.cssの中身
* {
margin: 0;
padding: 0; }
img {
max-width: 100%; }
.backgroundBox {
background-color: whitesmoke; }
.Container {
margin: 0 10px 20px;
padding-top: 10px;
padding-bottom: 10px; }
.top {
margin: 0 auto;
position: relative;
background-image: url("../images/file1/sample.png");
background-size: cover;
height: 254px;
width: 380px; }
.top::before {
content: "";
color: transparent;
background-color: rgba(60, 60, 55, 0.5);
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0; }
.top:hover::before {
content: "SAMPLE";
line-height: 50px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
position: absolute;
top: 40%;
bottom: 40%;
left: 0;
right: 0;
transition: 0.5s;
text-align: center; }
<ポイント>
・top
①背景を適用
②高さを与える(divタグに高さを定義しないと高さ0で表示されません)
③relativeを定義しておく(疑似要素の配置にabsoluteを使うため)
・top::before
①疑似要素で背景に重ねたい色を決める
②absoluteを定義
③top,right,bottom,leftをすべて0とすることで、元の要素と同じ大きさの疑似要素になる
・top:hover::before
①top,right,bottom,leftの値を任意に調整することで、疑似要素の大きさを変更できる。
今回であれば、上から40%の位置~下から40%位置までを疑似要素の大きさに設定した。
②line-heightは疑似要素間の高さを設定することで、文字を疑似要素の中心(縦方向)にした。
top,right,bottom,leftを変更するだけで、疑似要素の覆う範囲を変更できるのでtransitionを使用した簡単なアニメーションにおすすめです。
※スマホ対応のためにひとまずontouchstart=””をいれてあります。こちらに関しては、別記事で…
以上。