CSS element overlap and z-index
January 26, 2012 21:23:56 Last update: January 26, 2012 21:23:56
In an HTML page, elements can overlap because of position styles. When there's an overlap, elements coming later in the HTML code are displayed on the top. This can be altered by specifying
However,
This is a test page:
Effects of
z-index in the CSS. Elements with higher z-index are placed on the top.
However,
z-index only works for elements that are not static positioned. Static positioned elements are always at the bottom compared to relative, fixed and absolute positioned elements.
This is a test page:
- Code
- Demo
<!DOCTYPE html> <html> <head> <style type="text/css"> body { font-family: sans-serif; } div.big { position: absolute; width: 200px; height: 200px; border: 1px solid #999; background-color: #ddd; } div.small { width: 80px; height: 20px; padding: 4px; margin: 4px; border: 1px solid #002E00; background-color: #009900; } div.relative { position: relative; } </style> <script type="text/javascript"> function toggleAbsDiv() { var bg = document.getElementById("bg"); if (bg.style.display == 'none') { bg.style.display = ''; } else { bg.style.display = 'none'; } } </script> </head> <body> <button onclick="toggleAbsDiv();">Toggle Absolute Div</button> <div id="bg" class="big"></div> <div class="small">static</div> <div class="small relative">relative</div> </body> </html>
Effects of
z-index can be tested by adding it to the elements, for example:
<div id="bg" class="big" style="z-index: 3"></div> <div class="small" style="z-index: 6">static</div> <div class="small relative" style="z-index: 3">relative</div>