今回は『position』でよく使用する要素の配置をご紹介します。
「position:absolute;」
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">
<div class="Box2">box2</div>
</div>
</div>
</div>
</main>
</body>
</html>
<ポイント>
・Box1を親要素として、子要素Box2がある
<css>
* {
margin: 0;
padding: 0;
}
.backgroundBox {
background-color: whitesmoke;
}
.Container {
margin: 0 10px 20px;
padding-top: 10px;
padding-bottom: 10px;
}
.Box1 {
display: block;
width: 200px;
height: 100px;
background-color: green;
color: white;
position: relative;
z-index: 1000;
}
.Box2 {
display: block;
width: 60px;
height: 20px;
line-height: 20px;
text-align: center;
background-color: blue;
color: white;
position: absolute;
z-index: 10;
}
<ポイント>
・親要素Box1にposition:relative;、子要素Box2にposition:absolute;を指定。これにより、子要素の位置は親要素の上の左端に移動させることができる。
⇒親要素に背景を指定していれば、背景の上で子要素をレイアウトし易い。
<absoluteを使用した例>
box2
<absoluteを使用した例のcss>
* {
margin: 0;
padding: 0;
}
.backgroundBox {
background-color: whitesmoke;
}
.Container {
margin: 0 10px 20px;
padding-top: 10px;
padding-bottom: 10px;
}
.Box1 {
display: block;
width: 200px;
height: 100px;
background-color: green;
color: white;
position: relative;
z-index: 1000;
}
.Box2 {
display: block;
width: 60px;
height: 20px;
line-height: 20px;
text-align: center;
background-color: blue;
color: white;
position: absolute;
z-index: 10;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<ポイント>
・top、left、transformを追加して、子要素であるbox2を親要素box1の中心に配置
※ただしimgタグは子要素を入れることはできないため、そのときはposition:relative;で対応しましょう。⇒z-indexについて
今回は以上です。
ps
positionを使いこなすって難しいよね