今回は『z-index』を使用した要素の重ね方をご紹介します。
(完成イメージです)
box1
box2
<html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>タイトル</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<main>
<div class="backgroundBox">
<div class="Container">
<div class="Box1">
<p>box1</p>
</div>
<div class="Box2">
<p>box2</p>
</div>
</div>
</div>
</main>
</body>
</html>
<css①>
* {
margin: 0;
padding: 0;
}
.backgroundBox {
background-color: whitesmoke;
}
.Container {
margin: 0 10px 20px;
padding-top: 10px;
padding-bottom: 10px;
}
.Box1 {
display: block;
width: 100px;
height: 100px;
background-color: green;
color: white;
}
.Box2 {
display: block;
width: 100px;
height: 100px;
background-color: blue;
color: white;
}
<イメージ①>
box1
box2
<ポイント>
・100pxの正方形が二つ並んでいます。
<css②>
* {
margin: 0;
padding: 0;
}
.backgroundBox {
background-color: whitesmoke;
}
.Container {
margin: 0 10px 20px;
padding-top: 10px;
padding-bottom: 10px;
}
.Box1 {
display: block;
width: 100px;
height: 100px;
background-color: green;
color: white;
position: relative;
z-index: 1000;
}
.Box2 {
display: block;
width: 100px;
height: 100px;
background-color: blue;
color: white;
posision: relative;
z-index: 10;
}
<イメージ②>
box1
box2
<ポイント>
・重ねたい要素に「position」を追加
今回はbox1とbox2にposistion:relative;を追加
・重ねたい要素に「z-index」を追加
上にしたい要素の数値を大きくする
※z-indexはpositionを指定した要素のみ適用される。
<css③>
* {
margin: 0;
padding: 0;
}
.backgroundBox {
background-color: whitesmoke;
}
.Container {
margin: 0 10px 20px;
padding-top: 10px;
padding-bottom: 10px;
}
.Box1 {
display: block;
width: 100px;
height: 100px;
background-color: green;
color: white;
position: relative;
z-index: 1000;
}
.Box2 {
display: block;
width: 100px;
height: 100px;
background-color: blue;
color: white;
position: relative;
z-index: 10;
top: -20px;
left: 20px;
}
<完成イメージ>
box1
box2
<ポイント>
・Box2の要素を初期位置から上に-20px、左から20px移動
これを応用すれば、画像の上にテキストを自由に配置できるので、よく使用するかと思います。
以上です。
ps
忙しくて更新をさぼってしまった…