ttmt
ttmt

Reputation: 4984

CSS absolute position, z-index

This must be really simple but I'm stuck.

I have a header and below I have a full height/width block that is absolutely positioned. This will be a map but I have just used a coloured block to make it simple.

On top of this background I need the page that is 100% height in the middle. I thought I could use the z-index to show this on top of the absolutely positioned background but the page is always behind the 'bg' div

I know I'm missing something simple

*{
  margin: 0;
  padding: 0;
}

html, body{
  height: 100%;
}

.header{
  background: black;
  height: 50px;
  width: 100%;
}

.bg{
  background: red;
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
}

.page{
  background: grey;
  height: 100%;
  margin: 0 auto;
  width: 500px;
  z-index: 10;
}
<div class="header"></div>

<div class="bg"></div>

<div class="page"></div>

Upvotes: 3

Views: 5588

Answers (2)

Touffy
Touffy

Reputation: 6561

z-index has no effect on statically-positioned elements (which is the default). It affects relative, absolute and fixed ("positioned") elements. A common hack would be to add position:relative to your .page.

Upvotes: 9

Mohammed Wahed Khan
Mohammed Wahed Khan

Reputation: 898

To force an absolute positioned element for indexing you could use it in negative.

*{
  margin: 0;
  padding: 0;
}

html, body{
  height: 100%;
}

.header{
  background: black;
  height: 50px;
  width: 100%;
}

.bg{
  background: red;
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
}

.page{
  background: grey;
  height: 100%;
  margin: 0 auto;
  width: 500px;
  z-index: 10;
}
<div class="header"></div>

<div class="bg"></div>

<div class="page"></div>

Upvotes: 3

Related Questions