Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS absolute position, z-index

Tags:

css

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>
like image 355
ttmt Avatar asked Nov 06 '25 10:11

ttmt


2 Answers

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.

like image 193
Touffy Avatar answered Nov 09 '25 08:11

Touffy


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>
like image 20
Mohammed Wahed Khan Avatar answered Nov 09 '25 08:11

Mohammed Wahed Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!