Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put a static div on top of an absolute position div?

Tags:

html

css

I am building a small web application. I have two divs. One is absolute and the other is static. I am trying to position my static div on top of my absolute one, so that it remains the top most item.

Very simple Code Sample:

http://jsbin.com/efuxe3/edit

How can this be done?

Edit: I have been using z-index. It seems to have no effect.

like image 345
vondip Avatar asked May 07 '11 22:05

vondip


People also ask

How do I put something on top of a div?

You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).

Can a div be absolute and relative at the same time?

If you position it as relative , then you're moving it from its "normal" place (according to the page's flow). If you position it as absolute , then you're positioning it relative to its closest ancestor which is fixed or relative ... Clearly, nothing can be absolute and relative at the same time.

How do you position an element with an absolute position?

Absolute An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element. If it doesn't have any parent elements, then the initial document <html> will be its parent.


2 Answers

z-index doesn't apply to static elements.

According to this page:

This property specifies the stack level of a box whose position value is one of absolute, fixed, or relative.

If you make your div relative instead, you can use z-index to determine the order.

position: relative positions the element relative to its default (static) position, so if you don't specify a top, bottom, left or right then there'll be no difference between static and relative other than that relative allows you to use z-index to move your element up the stack.

Edit: based on your code sample, here's a working demo.

Edit 2: based on Nathan D. Ryan's suggestion in the comments below, you could also apply a negative z-index to your absolutely-positioned div. This would move it behind everything else on the page that didn't have a lower z-index defined.

like image 120
Town Avatar answered Sep 21 '22 12:09

Town


Rather than placing the statically positioned element over the absolutely positioned element, you can place the absolutely positioned element behind the statically positioned element. You can do this by setting the z-index of the absolutely positioned element to a negative value. However, as @Town mentioned, this will also place the absolutely positioned element behind everything else in the normal flow.

like image 32
Nathan Ryan Avatar answered Sep 22 '22 12:09

Nathan Ryan