LoginSignup
5
4

More than 5 years have passed since last update.

HTML&CSS 重なり順を指定する

Last updated at Posted at 2018-04-10

はじめに

CSSのz-indexを使って、
「例えばパワポの最前面に移動、前面に移動」のように簡単に重なり順を指定する方法をまとめました。

また、前回の「rgbaを使って背景画像を暗くする」の記事の続きになっています。
https://qiita.com/szaizen/items/3ab28c03a76e08bb5581

z-index

z-indexは要素の重なり順を決めることのできるプロパティです。

test {
  z-index: 数字;
}

数字で指定した値が大きい要素ほど上に表示されます。
これを使うだけで簡単に重なり順が指定できる、、、はず。
次、実践してみます。

実践例

スクリーンショット 2018-04-10 20.59.31.png

html
<body>
<div class="back">
  <h1 class="title">パソコン教室</h1>
  <p>Learn together!</p>
</div>
</body>
css
body{
  height: 100%;
  margin: 0;
}
.back{
  /* 画面いっぱいに背景画像を貼り付ける */
  background: url(http://simplemodern-interior.jp/knowledge/wp-content/uplads/2014/07/pc.png) no-repeat center;
  background-size: cover;
  position: relative;
  height:100%;
}
.back::before{
  /* 透過した黒を上から重ねるイメージ */
  background-color: rgba(0,0,0,0.4);
  /* 自由に位置指定 */
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  content: ' ';
}

前回、rgbaを使って背景画像を暗くしました。
しかし、文字まで暗くなって見にくいので、最前面に出したいと思います。

position: absolute;

スクリーンショット 2018-04-10 21.32.11.png

css
.title{
    position: absolute;
    width: 100%;
    text-align: center;
}

このように記述します。
この場合順番通りなのでうまく前面に表示されますが、HTMLが以下のような場合は背景画像に回り込んで表示されなくなってしまいます。

html
<body>
<h1 class="title">パソコン教室</h1>
<div class="back">
    <p>Learn together!</p>
</div>
</body>

z-indexで重なり順を指定する

そこで登場するのがz-indexさん。
ちなみにpositionがデフォルトのstaticだと適用されません。

なのでz-indexを追加すると、、

css
.title{
    position: absolute;
    width: 100%;
    text-align: center;
    /* 重なり順を指定*/
    z-index: 1;
}

ちゃんと表示できました!!!!

参考サイト

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4