Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I cover one div with another via z-index

Tags:

html

css

z-index

Referring in this instance

I can not get the div with id="covered" on top of the div with id="cover" simply by using the z-index.

Is there any other solution?

Code from http://codepen.io/anon/pen/jhgtf :

HTML:

<div id="cover"></div>
<div id="covered"></div>

CSS:

#cover{
  position:fixed;
  width:800px;
  background:black;
  height:350px;
  z-index:10;
}
#covered{
  width:80px;
  background:yellow;
  height:50px;
  z-index:11;
}
like image 807
sunjj8 Avatar asked Jan 22 '14 19:01

sunjj8


People also ask

How do I overlay one div over another?

By using a div with style z-index:1; and position: absolute; you can overlay your div on any other div . z-index determines the order in which divs 'stack'. A div with a higher z-index will appear in front of a div with a lower z-index . Note that this property only works with positioned elements.

How do I bring a div in front of another div?

Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values. Note that for this to work, you also need to set a position style ( position:absolute , position:relative , or position:fixed ) on both/all of the elements you want to order.

Why Z index is not working with div?

The root element forms the root stacking context. Other stacking contexts are generated by any positioned element (including relatively positioned elements) having a computed value of 'z-index' other than 'auto'. Stacking contexts are not necessarily related to containing blocks.

How do I position a div under one another?

If you want the two div s to be displayed one above the other, the simplest answer is to remove the float: left; from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.


2 Answers

You need to specify a position on #covered:

#cover{
  position:fixed;
  width:800px;
  background:black;
  height:350px;
  z-index:10;
}
#covered{
  position: fixed;
  width:80px;
  background:yellow;
  height:50px;
  z-index:11;
}

CodePen example

Elements with static (default) positioning are not affected by z-index - only positioned elements with fixed, relative, or absolute positioning are. Which of those you should use is dependent on context.

Official z-index specification

like image 110
Ennui Avatar answered Sep 25 '22 20:09

Ennui


#covered{
  position:relative;
  width:80px;
  background:yellow;
  height:50px;
  z-index:11;
}
like image 41
skshoyeb Avatar answered Sep 26 '22 20:09

skshoyeb