今回は、positionとz-indexを使用してコンテンツを重ねたコーディングの例を紹介します。
動作サンプルを見ていただくと、一番外側に影のようなものがあります。
影はbox-shadowを使用することで作成できますが、今回のコーディングはもう少し自由度が高いのではないかと思います。
posiotionとz-indexの基本的な使い方はこちらを参考にしてください。
<html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/common.css">
<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="mainContentsContainer">
<div class="mainContentsBox">
<h1 class="topTitle">サンプルタイトル</h1>
<h2 class="firstTitle">サンプルタイトル1</h2>
<div class="contentsBox">
<p>テキストテキストテキストテキストテキストテキスト</p>
<div class="imgBox"><img src="images/sample.png"></div>
</div>
<h2 class="secondTitle">サンプルタイトル2</h2>
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
<div class="outLayer"></div>
</div>
</div>
</div>
</div>
</main>
<!--footer-->
<footer></footer>
<body>
</html>
<ポイント>
div class=”outLayer”は中にコンテンツがないけど忘れないでください
<css>
* {
margin: 0;
padding: 0; }
img {
max-width: 100%; }
html {
font-size: 62.5%; }
.Container {
max-width: 780px;
margin: 0 auto;
padding-top: 30px;
padding-bottom: 50px; }
.mainContentsContainer {
padding: 0 30px; }
.mainContentsBox {
border: solid 1px blue;
max-width: 600px;
padding: 25px 15px;
margin: 0 auto;
position: relative;
background-color: white; }
.topTitle {
position: absolute;
top: -15px;
left: -15px;
z-index: 100;
padding: 1px 20px 0;
border: dashed 1px green;
background-color: white; }
.contentsBox {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
justify-content: space-between; }
.imgBox {
max-width: 200px; }
.text {
max-width: 380px;
font-size: 1.5rem;
padding-left: 10px; }
.firstTitle {
text-align: center;
font-size: 2.0rem; }
.outLayer {
position: absolute;
background-color: #afb3c7;
top: 10px;
bottom: -5px;
left: 20px;
right: -5px;
z-index: -10; }
<ポイント>
・mainContentsBoxを親要素として、それ以降の子要素で適当にレイアウトするために
position:relative;
を指定。
・outLayerはmainContentsBoxの子要素であるため、position:absolute;を指定し、
top: 10px;
right: -5px;
bottom: -5px;
left: 20px;
z-indexを指定し、背景色をmainContentsBoxより後ろにする。
⇒はみ出た部分が影のようになっています。
※
top: 0;
right: 0;
bottom: 0;
left: 0;
とすると、mainContentsBox要素全体を覆うサイズを指定できる。
⇒これが結構便利でした。
⇒mainContentsBoxの高さと大きさを判定してくれるので、レスポンシブデザインには割かし使えるかな。
今回は以上です。