Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my element with position:absolute always showing up underneath position:relative items?

Tags:

html

css

xhtml

It's all in the question but here's a simple example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" />
    <title>TEST</title>
</head>
<body style="margin:0;padding:0">

<div style="background-color:#eeeeee;margin:auto;height:500px;width:500px">
    <div style="position:relative">
        <span style="position:absolute;display:block;height:250px;width:250px;background:green;z-layer:2"><br /><br />Should be on top</span>
    </div>
    <span style="position:relative;display:block;width:500px;background:blue;z-layer:1">Actually on top</span>
</div>

</body>
</html>
like image 262
Andrew G. Johnson Avatar asked Dec 09 '22 21:12

Andrew G. Johnson


2 Answers

instead of "z-layer" use "z-index"

also the absolute span is in a relative div with no z-index

Here is the correct html:

<div style="background-color:#eeeeee;margin:auto;height:500px;width:500px">
    <div style="position:relative;z-index:2">
        <span style="position:absolute;display:block;height:250px;width:250px;background:green"><br /><br />Should be on top</span>
    </div>
    <span style="position:relative;display:block;width:500px;background:blue;z-index:1">Actually on top</span>
</div>
like image 111
Jeremy Boyd Avatar answered May 15 '23 16:05

Jeremy Boyd


It happens because when you position an element "absolutely" it is removed from the flow of the document in the Document Object Model and so elements that remain in the flow of the document appear "above" the removed element. For cross-browser compatibility place your z-index adjustments on the parent element of the absolutely positioned element.

like image 29
Nick Allen Avatar answered May 15 '23 17:05

Nick Allen